DelphiFAQ Home Search:
General :: Web publishing :: JavaScript :: Events
Questions, answers and code examples dealing with javascript event handlers.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

How do I add a javascript event handler on the fly (at runtime)?

Question:

I need to attach an event handler at runtime, the idea is that depending on user action, I want different handlers to be assigned. But it seems not to work?

Answer:

Below is some javascript code that will work. It was tested with Firefox and IE 6. It seems not to be possible to assign the handler in the links' onclick() itself e.g.

href="javascript:document.sampleImage.onclick=Handler1; "

does NOT work! Common other errors are to actually call the event handler in the assignment statement by appending the () or to write the to-be-assigned event handler as a string (encapsulating it with " or ').

Assigning in a function body as shown below works as expected.

<html>
 <body>
 <img name="sampleImage" width=30 height=20 border=1 src="someimage.gif"><br>
 
 <script language="JavaScript" type="text/javascript">
 <!--
 function Handler1 (evt) {
   alert('clicked image (1)'); 
 }
 
 function Handler2 (evt) {
   alert('clicked image (2)'); 
 }
 
 function assign_handler_1() {
   document.sampleImage.onclick=Handler1;  
 }
 function assign_handler_2() {
   document.sampleImage.onclick=Handler2;
 }
 // end hiding contents -->
</script>
 
 <a href="javascript:assign_handler_1()">activate handler 1</a>
 <br>
 <a href="javascript:assign_handler_2();">activate handler 2</a>
 
 </body>
 </html>
 

Generated 16:02:17 on Jan 21, 2018