Skip to content

Instantly share code, notes, and snippets.

@vitkarpov
Last active December 17, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitkarpov/5684042 to your computer and use it in GitHub Desktop.
Save vitkarpov/5684042 to your computer and use it in GitHub Desktop.
Extend jQuery.Event object with custom event
(function ($) {
//cache native handler for click
var nativeHandler;
$.event.special.leftClick = {
//init event for the DOM element
setup: function (r) {
$(this).bind('click', eventHandler);
},
//destroy event for the DOM element
teardown: function () {
$(this).unbind('click', eventHandler);
},
//add some functionality to event's trigger
add: function (handleObj) {
//cache native handler for call it later
nativeHandler = handleObj.handler;
}
};
//event handler
function eventHandler(e) {
//cache "click" type
var cachedType = e.type;
//e.button = 0 for left button, so
//we won't do anything if it's not left click
if (e.button || e.offsetX < 0) {
return false;
}
//change event type
//so we can define it in handlers
e.type = "leftClick";
//call native handler
nativeHandler.apply(this, arguments);
//return "click" type, for other click handlers
e.type = cachedType;
}
})(jQuery);
@vitkarpov
Copy link
Author

leftClick handler will ba called only on left mouse click: no other mouse buttons or firing usual click event with keyboard or smth else

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment