Adding an Event HandlerQuestion: 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: <a href="gothere.htm" onlick="alert('Bye!')">Click me!</a> 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 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
You can combine the above calls together in a cross-browser function 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 © 1999-2011, JavaScripter.net.