Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to off a jquery event then on it again?

Tags:

jquery

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?

like image 659
Robson Silveira Avatar asked Apr 02 '12 02:04

Robson Silveira


2 Answers

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>
like image 178
Greg Pettit Avatar answered Nov 09 '22 00:11

Greg Pettit


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);
like image 2
bfavaretto Avatar answered Nov 09 '22 01:11

bfavaretto