Skip to content

Instantly share code, notes, and snippets.

@matijs matijs/click-handler.js
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.