Advertisement
  1. Code
  2. JavaScript

JavaScript from Null: Cross-Browser Event Binding

Scroll to top
Read Time: 1 min
This post is part of a series called Javascript from Null.
JavaScript from Null: Chapter 5 – Events
JavaScript from Null: Utility Functions and Debugging

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 &#038;&#038; !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
Did you find this post useful?
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.
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.