Saeid Khaleghi
Saeid Khaleghi

Reputation: 175

jQuery : Kill Mouseenter/mouseleave function on mouseleave

I have some issues with mouseenter/mouseleave function.

please take a look at my code;

$(".elms").live(
{
    mouseenter: function (e) 
    {
        $("a").click(function()
        {
            alert('test');
        });
    },
    mouseleave: function (e) 
    {
        //do something else
    }
});

html :

<div class='elms'>test [ function says `test` ]</div>
<div class='elms'>test [ function says `test` and `test` ]</div>
<div class='elms'>test [ function says `test` and `test` and `test` ]</div>
<div class='elms'>test [ function says `test` and `test` and `test `test` and `test` ]</div>

and this will repeat for even 90 elements , i want to kill function on leave and make new one. Something like this :

var killIt = $(".elms").live(
{
    mouseenter: function (e) 
    {
        $("a").click(function()
        {
            alert('test');
        });
    },
    mouseleave: function (e) 
    {
        killIt.die();
    }
});

Any ideas?

[ Fiddle : http://jsfiddle.net/29f3P/ ]

Upvotes: 0

Views: 410

Answers (2)

deweyredman
deweyredman

Reputation: 1450

I'm not sure this is what you want, in this case you are adding a listener each time you mouse over the .elms element. If you truly want to add a listener each time you mouse over and you don't want the repeated behavior you are seeing can use bind and unbind to set your mouse events as described here:

$(".elms").live({
        mouseenter: function (e) {
             $("a").bind("click", function(){
                  alert('test');
             });

        },
        mouseleave: function (e) {
             $("a").unbind("click");

        }

});

I modified your fiddle here:

Upvotes: 1

Michael Benjamin
Michael Benjamin

Reputation: 2915

If you must destroy the listener each time, try jQuery.one(), which will destroy the listener automatically after the first call.

http://api.jquery.com/one/

If the listener does not necessarily run one time, try jQuery.off() to unbind the listener.

http://api.jquery.com/off/

Upvotes: 0

Related Questions