Created
February 28, 2012 11:14
-
-
Save madr/1931955 to your computer and use it in GitHub Desktop.
Click listener and delegator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
light-weight click listener, v 1.0 | |
Copyright (c) 2010 by madr <http://madr.se> | |
Licensed under the MIT license: http://en.wikipedia.org/wiki/MIT_License | |
*/ | |
/* | |
Usage: | |
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. | |
*/ | |
(function(document, undefined) { | |
function investigate(elm){ | |
/* | |
Change the content of this function | |
to suit your web application. | |
*/ | |
/* | |
EXAMPLE 0: do nothing until jQuery (or other libraries) is loaded. | |
if (typeof window.jQuery == 'undefined') { return false; } | |
*/ | |
/* | |
EXAMPLE 1: look for element type | |
if (elm.nodeName == 'A') { | |
// do stuff ... | |
return true; | |
} | |
*/ | |
/* | |
EXAMPLE 2: look for id or other property | |
if (elm.id == 'modal-window-opener') { | |
// do stuff ... | |
return true; | |
} | |
*/ | |
/* | |
EXAMPLE 3: sniffing a classname | |
if (elm.className.match(/read-more/)) { | |
// do stuff ... | |
return true; | |
} | |
*/ | |
return false; // default | |
} | |
function clicklistener(evt){ | |
var event = evt || window.event, | |
elm = event.target || window.srcElement, | |
magic_did_happen = investigate(elm); | |
if (magic_did_happen) { | |
if (window.event) { window.eventReturnValue = false; } | |
else { evt.preventDefault(); } | |
return false; | |
} | |
} | |
if (document.attachEvent) { | |
document.attachEvent('onclick', clicklistener); | |
} else { | |
document.addEventListener('click', clicklistener, false); | |
} | |
})(document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment