Video icon 64
Learning to code? Skill up faster with our practical video courses. Start your free trial today.
Advertisement

JavaScript from Null: Cross-Browser Event Binding

by
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

  
var addEvent = (function( window, document ) { 
	if ( document.addEventListener ) { 
		return function( elem, type, cb ) { 
			if ( (elem && !elem.length) || elem === window ) { 
				elem.addEventListener(type, cb, false ); 
			} 
			else if ( elem && elem.length ) { 
				var len = elem.length; 
				for ( var i = 0; i < len; i++ ) { 
					addEvent( elem[i], type, cb ); 
				} 
			} 
		}; 
	} 
	else if ( document.attachEvent ) { 
		return function ( elem, type, cb ) { 
			if ( (elem &#038;&#038; !elem.length) || elem === window ) { 
				elem.attachEvent( 'on' + type, function() { return cb.call(elem, window.event) } ); 
			} 
			else if ( elem.length ) { 
				var len = elem.length; 
				for ( var i = 0; i < len; i++ ) { 
					addEvent( elem[i], type, cb ); 
				} 
			} 
		}; 
	} 
})( this, document ); 
// Example Usage 
var lis = document.getElementsByTagName('li'); 
addEvent( window, 'click', function() { 
	this.style.border = '1px solid red'; 
  
});

Please note that this code is slightly revised, based upon some excellent feedback in the comments section.

Advertisement