addEvent Function


/ Published in: JavaScript
Save to your folder(s)

addEvent function. Can't remember the exact site i got it from. Works well for me.


Copy this code and paste it in your HTML
  1. //The addEvent function for page loading an onclicks
  2. function addEvent( obj, type, fn ) {
  3. if (obj.addEventListener) {
  4. obj.addEventListener( type, fn, false );
  5. EventCache.add(obj, type, fn);
  6. }
  7. else if (obj.attachEvent) {
  8. obj["e"+type+fn] = fn;
  9. obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
  10. obj.attachEvent( "on"+type, obj[type+fn] );
  11. EventCache.add(obj, type, fn);
  12. }
  13. else {
  14. obj["on"+type] = obj["e"+type+fn];
  15. }
  16. }
  17. var EventCache = function(){
  18. var listEvents = [];
  19. return {
  20. listEvents : listEvents,
  21. add : function(node, sEventName, fHandler){
  22. listEvents.push(arguments);
  23. },
  24. flush : function(){
  25. var i, item;
  26. for(i = listEvents.length - 1; i >= 0; i = i - 1){
  27. item = listEvents[i];
  28. if(item[0].removeEventListener){
  29. item[0].removeEventListener(item[1], item[2], item[3]);
  30. };
  31. if(item[1].substring(0, 2) != "on"){
  32. item[1] = "on" + item[1];
  33. };
  34. if(item[0].detachEvent){
  35. item[0].detachEvent(item[1], item[2]);
  36. };
  37. item[0][item[1]] = null;
  38. };
  39. }
  40. };
  41. }();
  42. addEvent(window,'unload',EventCache.flush);
  43.  
  44. //usage
  45. addEvent(window, 'load', functionName);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.