Skip to content

Instantly share code, notes, and snippets.

@matijs
Last active August 29, 2015 14:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matijs/5b2d6675265ec440bcba to your computer and use it in GitHub Desktop.
Save matijs/5b2d6675265ec440bcba to your computer and use it in GitHub Desktop.
jQuery-based method for handling clicks declared with a data-attribute
$(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