Cross Browser Event Management Functions Using JavaScript | ||
| ||
| approach to attach and manage events. IE uses Object.attachEvent to attach an event to an object,whereas Fx uses Object.addEventListener to do the above function. Similarly the functions used for removing an attached event also varies. What I have provided is a crossbrowser function addEvent which will call the function specific for that browser. Similarly calling the function preventDefault from an attached event handle prevents the triggering of the default action associated with that event. <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <title>Cross Browser Event Management</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <script type="text/javascript"> <!-- /* Cross Browser Event Management */ function addEvent(el,evType,handle){ if(el.addEventListener)el.addEventListener(evType,handle,false); else if(el.attachEvent){ el["e" evType handle] = handle; el[evType handle] = function(){el["e" evType handle](window.event)} el.attachEvent("on" evType,el[evType handle]); } } function removeEvent(el,evType,handle){ if(el.removeEventListener)el.removeEventListener(evType,handle,false); else if(el.detachEvent){ el.detachEvent("on" evType,el[evType handle]) el[evType handle] = null el["e" evType handle] = null; } } function preventDefault(evt){ var e = evt ? evt : window.event; if(e.preventDefault){ e.preventDefault(); }else{ e.returnValue = false; } } function stopPropagation(evt){ var e = evt ? evt : window.event; if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBubble = true; } } function init(){ addEvent(document.getElementById('ElemId'),'click',clickTest); } function clickTest(){ alert('Clicked'); removeEvent(document.getElementById('ElemId'),'click',clickTest); alert('Removed'); } addEvent(window,'load',init); //--> </script> </head> <body onload=""> <div id="ElemId" style="width:200px;height:50px;border:1px #CCC solid;background:#F2F2F2;">Click Me</div> </body> </html> | ||
| | ||
| |