I would like to unbind an event on a div that contains a button when this button is clicked
I am using this piece of code but it doesn’t seem to work, the event keeps being attached to the button container:
$('body').on('click', '.button', function(){
$('body').off('mouseleave',$(this).closest('.button-container'));
});
what am I doing wrong?
fiddle link: http://jsfiddle.net/y3a6N/3/
Thanks
You can’t use
.on()and.off()that way. Your.on()code is a delegated handler:It’s an event handler attached to the body object and looking for hover events from any element with class of “button-container”.
You cannot then just do
.off()on one particular element like you are trying to do with this:That doesn’t match the
.on()signature so there’s no matching event handler to remove. With delegated event handler (like you’re using here with.on()), it’s either all of nothing. You either remove the entire event handler or not. You can’t tell it to just stop delegating on behalf of only some objects.If your objects are not dynamic and thus you don’t need delegated event handling, you can do this to remove the specific event handler you want to remove:
Working jsFiddle here: http://jsfiddle.net/jfriend00/R2eQx/.
Another approach that might be simpler is to just remove the class from the object like this:
And a working jsFiddle here: http://jsfiddle.net/jfriend00/byFpx/.
This leaves the event handler in place, but just removes the triggering class from the button-container so it won’t match the event handler any more. This makes it easier to make it trigger again by just adding the class back again.