I've added an event listener like this:
$('body').on('mouseenter','.classname',function() { /* code */ });
Then I've removed it like this:
$('.classname').off('mouseenter');
Now I'd like to turn it on again. I've tried this:
$('.classname').on('mouseenter');
...but it didn't work.
How can I do it?
Not like that, no. When you off it, you are destroying the event. It's not stored in memory as something that can just be reactivated like that. There are easy ways to simplify the mouseenter binding call, though.
Or, just use a flag in the mouseenter logic. If the flag is true, go ahead and do the rest of the stuff; otherwise, do nothing. The flag can easily be set by any other activity on your page.
Really simplified example of the flag method: http://jsfiddle.net/8YXFB/
var ontastic = true;
$(document).on('mouseenter', '.classname', function() {
if (ontastic) {
$('#output').append('<li>Moused!</li>');
}
});
$('#on').click(function() {
ontastic = true;
});
$('#off').click(function() {
ontastic = false;
});
(and the HTML, though you can probably figure it out without)
<div class="classname">Mouse me!</div>
<button id="on">MouseEnter On</button><br/>
<button id="off">MouseEnter Off</button>
<ul id="output">
<li>Initialized</li>
</ul>
Store the event listener in a variable instead of declaring it as an anonymous function, then reuse that:
var mouseenterListener = function() { /* code */ };
$('body').on('mouseenter', '.classname', mouseenterListener);
$('.classname').off('mouseenter');
// on again
$('body').on('mouseenter', '.classname', mouseenterListener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With