Adding an Event Handler

JavaScript FAQ | Keyboard & Mouse Events FAQ  

Question: How do I add a JavaScript event handler to an HTML page element?

Answer: The old-fashioned (and still widely supported) ways of registering event handlers for page elements are:

  • inline event handlers added as HTML tag attributes, for example:
     
 <a href="gothere.htm" onlick="alert('Bye!')">Click me!</a>
  • event handlers added by assignment (usually right after the page loads), e.g.:
     
 document.onclick=clickHandler;

 
 document.onkeydown=keyHandler;

The above techniques are simple but have certain disadvantages: they allow you to have just one event handler per element. In addition, with inline event handlers you get very poor separation of JavaScript code from HTML markup. Modern browsers provide additional programmatic ways of registering event handlers for page elements, allowing you to dynamically add one or more handlers during the webpage lifetime. For example, you can programmatically add

handlerFunction
as an
onclick
event handler for an
element
by using these methods:
element.attachEvent('onclick',handlerFunction);

   (in Internet Explorer 5 or newer)
element.addEventListener('click',handlerFunction,false);

   (in most non-IE browsers and IE9).

The third argument

false
in
addEventListener
specifies that the event capturing phase should not be used, and the event should be handled during the bubbling phase of the event propagation.

You can combine the above calls together in a cross-browser function

addEventHandler
:
function addEventHandler(elem,eventType,handler) {
 if (elem.addEventListener)
     elem.addEventListener (eventType,handler,false);
 else if (elem.attachEvent)
     elem.attachEvent ('on'+eventType,handler); 
}
Here is an example of calling the
addEventHandler
function to add event handlers to two buttons with
id="button1"
and
id="button2"
:
var sEventType = 'click';
var b1 = document.getElementById('button1');
var b2 = document.getElementById('button2');

addEventHandler(b1,sEventType,handlerFunction1);
addEventHandler(b2,sEventType,handlerFunction2);
Try adding event handlers for Button 1 and Button 2 here:
If you try to register the same event handler function for the same element more than once, the results will be browser-dependent: some browsers (e.g. IE8) would repeat the same handler as many times as you registered it; other browsers (e.g. Firefox 3) would only invoke each handler function once per event.

See also:

Copyright © 1996-2018, JavascriptFAQ.net.