Last active
August 29, 2015 14:09
-
-
Save matijs/5b2d6675265ec440bcba to your computer and use it in GitHub Desktop.
jQuery-based method for handling clicks declared with a data-attribute
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
$(function() { | |
'use strict'; | |
// generic click handler | |
$(document).on('click', '[data-handler]', function(event) { | |
var handler = this.getAttribute('data-handler'); | |
// honour default behaviour when using modifier keys when clicking | |
// for example: | |
// cmd + click / ctrl + click opens a link in a new tab | |
// shift + click opens a link in a new window | |
if (this.tagName === 'A' && (event.metaKey || event.ctrlKey || event.shiftKey)) { | |
return; | |
} | |
if (handlers && typeof handlers[handler] === 'function') { | |
handlers[handler].call(this, event); | |
} | |
else { | |
if (window.console && typeof console.log === 'function') { | |
console.log('Non-existing handler: "%s" on %o', handler, this); | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment