click listener and click event delegation function, library independent


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



Copy this code and paste it in your HTML
  1. /*!
  2. light-weight click listener, v 1.0
  3. Copyright (c) 2010 by madr <http://madr.se>
  4. Licensed under the MIT license: http://en.wikipedia.org/wiki/MIT_License
  5. */
  6. /*
  7. Usage:
  8. Alter the below snippet for your needs and put the modified snippet in a js-file or a <script> and add it to your document. If your webapp depends on libraries or other resources to load, you better keep that in mind.
  9. */
  10. (function(document, undefined) {
  11. function investigate(elm){
  12. /*
  13.   Change the content of this function
  14.   to suit your web application.
  15.   */
  16.  
  17. /*
  18.   EXAMPLE 0: do nothing until jQuery (or other libraries) is loaded.
  19.   if (typeof window.jQuery == 'undefined') { return false; }
  20.   */
  21.  
  22. /*
  23.   EXAMPLE 1: look for element type
  24.   if (elm.nodeName == 'A') {
  25.   // do stuff ...
  26.   return true;
  27.   }
  28.   */
  29.  
  30. /*
  31.   EXAMPLE 2: look for id or other property
  32.   if (elm.id == 'modal-window-opener') {
  33.   // do stuff ...
  34.   return true;
  35.   }
  36.   */
  37.  
  38. /*
  39.   EXAMPLE 3: sniffing a classname
  40.   if (elm.className.match(/read-more/)) {
  41.   // do stuff ...
  42.   return true;
  43.   }
  44.   */
  45.  
  46. return false; // default
  47. }
  48.  
  49. function clicklistener(evt){
  50. var event = evt || window.event,
  51. elm = event.target || window.srcElement,
  52. magic_did_happen = investigate(elm);
  53.  
  54. if (magic_did_happen) {
  55. if (window.event) { window.eventReturnValue = false; }
  56. else { evt.preventDefault(); }
  57.  
  58. return false;
  59. }
  60. }
  61.  
  62. if (document.attachEvent) {
  63. document.attachEvent('onclick', clicklistener);
  64. } else {
  65. document.addEventListener('click', clicklistener, false);
  66. }
  67. })(document);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.