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


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)?


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?


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.

 <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() {
 function assign_handler_2() {
 // end hiding contents -->
 <a href="javascript:assign_handler_1()">activate handler 1</a>
 <a href="javascript:assign_handler_2();">activate handler 2</a>

Generated 0:01:46 on Sep 30, 2020