JS - Turn events on/off


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



Copy this code and paste it in your HTML
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml" >
  3. <head>
  4. <title>Simple Event Example</title>
  5. <script type="text/javascript">
  6. function addEventHandler(oNode, evt, oFunc, bCaptures)
  7. {
  8. if (typeof(oNode.attachEvent) != "undefined")
  9. oNode.attachEvent("on"+evt, oFunc);
  10. else
  11. oNode.addEventListener(evt, oFunc, bCaptures);
  12. }
  13. function removeEventHandler(oNode, evt, oFunc, bCaptures) {
  14. if (typeof (oNode.detachEvent) != "undefined")
  15. oNode.detachEvent("on" + evt, oFunc);
  16. else
  17. oNode.removeEventListener(evt, oFunc, bCaptures);
  18. }
  19. function getEventTarget(e) {
  20. if ((window.event) && (window.event.srcElement)) return window.event.srcElement;
  21. else return e.target;
  22. }
  23.  
  24. function onLinkClicked(e) {
  25. alert("You clicked the link!");
  26. }
  27. function onEnableClick(e) {
  28. var target = getEventTarget(e);
  29. if (target.checked)
  30. addEventHandler(document.getElementById("clickLink"), "click", onLinkClicked, false);
  31. else
  32. removeEventHandler(document.getElementById("clickLink"), "click", onLinkClicked, false);
  33. }
  34.  
  35. function setUpClickEvent(e) {
  36. addEventHandler(document.getElementById("Checkbox1"), "click", onEnableClick, false);
  37. }
  38.  
  39. addEventHandler(window, "load", setUpClickEvent, false);
  40. </script>
  41. </head>
  42. <body>
  43. <a href="#" title="click me" id="clickLink">Click Me!</a>
  44. <p>
  45. <input id="Checkbox1" type="checkbox" />Enable click events</p>
  46. </body>
  47. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.