Posted By

Nettuts on 08/27/10


Tagged


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

vali29
korzhik
adardesign
qubestream
leobetosouza
AmosFiveSix


JS Cross-Browser Event Binding


 / Published in: JavaScript
 

  1. var addEvent = (function( window, document ) {
  2. if ( document.addEventListener ) {
  3. return function( elem, type, cb ) {
  4. if ( (elem && !elem.length) || elem === window ) {
  5. elem.addEventListener(type, cb, false );
  6. }
  7. else if ( elem && elem.length ) {
  8. var len = elem.length;
  9. for ( var i = 0; i < len; i++ ) {
  10. addEvent( elem[i], type, cb );
  11. }
  12. }
  13. };
  14. }
  15. else if ( document.attachEvent ) {
  16. return function ( elem, type, cb ) {
  17. if ( (elem && !elem.length) || elem === window ) {
  18. elem.attachEvent( 'on' + type, function() { return cb.call(elem, window.event) } );
  19. }
  20. else if ( elem.length ) {
  21. var len = elem.length;
  22. for ( var i = 0; i < len; i++ ) {
  23. addEvent( elem[i], type, cb );
  24. }
  25. }
  26. };
  27. }
  28. })( this, document );
  29. // Example Usage
  30. var lis = document.getElementsByTagName('li');
  31. addEvent( window, 'click', function() {
  32. this.style.border = '1px solid red';
  33.  
  34. });

Report this snippet  

You need to login to post a comment.