hellomello
hellomello

Reputation: 8585

can't unbind mouse leave when clicking

I have a jquery script, where if you mouseenter and element, something shows, and disappears when you mouseleave. I'm trying to unbind the mouseleave when user clicks, so that "something" stays showing when user leaves. Is this the correct way to do it? If so, can someone help me get this script to work?

Thank you!

$('.block').live("mouseenter",function(){
        var id= $(this).attr('id');
        $('#arrowPreview'+id).show();


    }).live("mouseleave",function(){
        var id= $(this).attr('id');
        $('#arrowPreview'+id).hide();

    }).live("click",function(){
        var id= $(this).attr('id');
        $('#arrowPreview'+id).show();
        $(this).unbind("mouseleave");
    });

Thank you!

Upvotes: 0

Views: 1514

Answers (3)

mrtsherman
mrtsherman

Reputation: 39872

So I don't think what you want is exactly possible. The problem appears to be the use of .live and unbind. You can unbind the mouseleave event with .die. However, the selector used must match the one originally used to bind the event, in your case .block. I am thinking that this obviously is bad. Example Fiddle of .die

http://jsfiddle.net/EZNDg/

I think that instead you need to bind using an explicit selector for the current element, so perhaps using .each with your selector and then binding with $(this). This should allow die to work. I will mess with this Fiddle and see if it is true.

Upvotes: 1

zzzzBov
zzzzBov

Reputation: 179046

events bound with live are unbound with die

Upvotes: 0

Justin
Justin

Reputation: 2103

You need to create the functions to execute on events as variables to ensure integrity of your javascript so for your example:

var fShow = function(){
    var id= $(this).attr('id');
    $('#arrowPreview'+id).show();
};

var fHide = function(){
    var id= $(this).attr('id');
    $('#arrowPreview'+id).hide();
};

var fClick = function(){        
    var id= $(this).attr('id');
    $('#arrowPreview'+id).show();
};

$('.block').bind('mouseenter',fShow);
$('.block').bind('mouseleave',fHide);
$('.block').unbind('mouseleave',fHide);

Upvotes: 2

Related Questions