JavaScript from Null: Cross-Browser Event Binding
Advertisement
Advertisement
Advertisement
Advertisement
Advertisement
Read Time:
1 min
This post is part of a series called Javascript from Null.
In chapter five of this series, we jumped into the muddy world of event listeners. In that episode, we only got our feet wet; however, today, we’ll take things a step further as we implement a far more efficient solution. Along the way, we’ll learn a plethora of new techniques.
Full Screencast

Our Final Code
1 |
|
2 |
var addEvent = (function( window, document ) { |
3 |
if ( document.addEventListener ) { |
4 |
return function( elem, type, cb ) { |
5 |
if ( (elem && !elem.length) || elem === window ) { |
6 |
elem.addEventListener(type, cb, false ); |
7 |
}
|
8 |
else if ( elem && elem.length ) { |
9 |
var len = elem.length; |
10 |
for ( var i = 0; i < len; i++ ) { |
11 |
addEvent( elem[i], type, cb ); |
12 |
}
|
13 |
}
|
14 |
};
|
15 |
}
|
16 |
else if ( document.attachEvent ) { |
17 |
return function ( elem, type, cb ) { |
18 |
if ( (elem && !elem.length) || elem === window ) { |
19 |
elem.attachEvent( 'on' + type, function() { return cb.call(elem, window.event) } ); |
20 |
}
|
21 |
else if ( elem.length ) { |
22 |
var len = elem.length; |
23 |
for ( var i = 0; i < len; i++ ) { |
24 |
addEvent( elem[i], type, cb ); |
25 |
}
|
26 |
}
|
27 |
};
|
28 |
}
|
29 |
})( this, document ); |
30 |
// Example Usage
|
31 |
var lis = document.getElementsByTagName('li'); |
32 |
addEvent( window, 'click', function() { |
33 |
this.style.border = '1px solid red'; |
34 |
|
35 |
});
|
Please note that this code is slightly revised, based upon some excellent feedback in the comments section.
Advertisement
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Sign upHi, I'm Jeffrey. I'm the creator of Laracasts and spend most of my days building the site and thinking of new ways to teach confusing concepts.
Advertisement
Advertisement
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.