Topic: Cross browser addEventListener function (Page 1 of 1) |
|
---|---|
Bipolar (III) Inmate From: |
posted 05-28-2010 20:43
I am working from a tutorial trying to write a cross browser addEventListener function. I see that it works in firefox and IE but not so good in safari. Can anyone tell me how to fix my code so that it works with safari? code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Simple Event Example</title> <script type="text/javascript"> function addEventHandler(oNode, evt, oFunc, bCaptures) { if (typeof(window.event) != "undefined") oNode.attachEvent("on"+evt, oFunc); else oNode.addEventListener(evt, oFunc, bCaptures); } function onLinkClicked(e) { alert("You clicked the link!"); } function setUpClickEvent(e) { addEventHandler(document.getElementById("clickLink"), "click", onLinkClicked, false); } addEventHandler(window, "load", setUpClickEvent, false); </script> </head> <body> <a href="#" title="click me" id="clickLink">Click Me!</a> </body> </html>
|
Bipolar (III) Inmate From: London |
posted 08-05-2010 21:26
Instead of testing for window.event, you are better off testing for the presence of the calls you wish to use: code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Simple Event Example</title> <script type="text/javascript"> function addEventHandler(oNode, evt, oFunc, bCaptures) { if (document.addEventListener) { // Safari, Chrome, Fx, etc oNode.addEventListener(evt, oFunc, bCaptures); } else if (document.attachEvent) { // IE oNode.attachEvent('on' + evt, oFunc); } else { // If all else fails oNode['on' + evt] = oFunc; } } function onLinkClicked(e) { alert("You clicked the link!"); } function setUpClickEvent(e) { addEventHandler(document.getElementById('clickLink'), 'click', onLinkClicked, false); } addEventHandler(window, 'load', setUpClickEvent, false); </script> </head> <body> <a href="#" title="click me" id="clickLink">Click Me!</a> </body> </html>
|
Nervous Wreck (II) Inmate From: |
posted 05-31-2011 11:00
Edit TP: spam removed
|