What is this function? Didn't really find any good examples.
The addEventListener
method is the W3C standard method to attach an event handler to an element, so that you can do something useful when an event is triggered. The following example would popup an alert message when the element with id my_image_id
is clicked:
function doSomething() {
alert('Image clicked');
}
var myImage = document.getElementById('my_image_id');
myImage.addEventListener('click', doSomething, false);
Unfortunately this does not work in Internet Explorer, since Microsoft uses a different event registration model. In Internet Explorer 5+, you would have to attach the event handler as follows:
myImage.attachEvent('onclick', doSomething);
Therefore for a cross browser event registration method, you can use reflection and execute conditionally:
function addEventHandler(node, type, f) {
if (node.addEventListener) {
node.addEventListener(type, f, false);
}
else if (node.attachEvent) {
node.attachEvent("on" + type, f);
}
else {
node["on" + type] = f;
}
}
var myImage = document.getElementById('my_image_id');
addEventHandler(myImage, 'click', doSomething);
Further reading:
You may be familiar with adding an event handler like this:
window.onload = function() {
alert('onload event!');
};
or even in HTML like this:
<body onload="alert('onload event!')">
Well, the downside to this is that you can only have one event handler. So if something else later overwrites that "onload" property, the previous event handler is no longer used.
addEventListener is a way to register an event handler without overwriting a previous one. It's supported by most browsers other than Internet Explorer. No to worry, though, because Internet Explorer has its own equivalent: attachEvent.
Here's a (simplified) example of their use:
if (myelement.addEventListener) {
// other browsers
myelement.addEventListener(eventname, callback, false);
}
else {
myelement.attachEvent("on"+eventname, callback);
}
It's usually a better idea to register an event using addEventListener or attachEvent methods than the onload/onsomething property because it will not possibly disrupt any other Javascript code from the same page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With