kapoko
kapoko

Reputation: 988

Jquery mouseleave event on two elements

I want to trigger an event when the mouse leaves two elements. I found the following jsfiddle which is exactly what I'm looking for:

http://jsfiddle.net/pFTfm/54/

It uses this code:

var count = 0;
$('#d1, #d2').mouseenter(function(){
    count++;
    $('#d3').show();
}).mouseleave(function(){
    count--;
    if (count == 0) { 
        $('#d3').hide();
        $('#d3').css('background-color', 'orange');
    }
});
​

However, the event still gets triggered, as you can see by the div changing its background color.

I want the event only to be triggered when the mouse really leaves both elements.

Upvotes: 1

Views: 4874

Answers (3)

Bruno
Bruno

Reputation: 5822

Another variation using .setTimeout()

var timer;

$('#d1, #d2').hover(function(){
    if( timer ) clearTimeout( timer );
    $('#d3').show();
},
function(){
    timer = setTimeout( function( ) {
        $('#d3').hide().css('background-color', 'orange');
    }, 100 );
});

Fiddle here

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108500

You can’t prevent the events from happening, but you can check the related target (the element you came from) and check if it’s one or the other. If it is, just return from the event handler.

Something like:

var checkRelated = function(e) {
    var id = e.relatedTarget.id;
    return id == 'd1' || id == 'd2';
}

$('#d1, #d2').mouseenter(function(e){
    if (checkRelated(e)) return;
    $('#d3').show();
}).mouseleave(function(e){
    if (checkRelated(e)) return;
    // now we know we actually left both elements
    $('#d3').hide();
});

Demo: http://jsfiddle.net/pFTfm/57/

Upvotes: 5

OpherV
OpherV

Reputation: 6937

How about:

var count=0;
$('#d1, #d2').mouseenter(function(){
    count++;
    $('#d3').hide();
}).mouseleave(function(){
    count--;

    setTimeout(function(){
        if (count==0){
                $('#d3').show();
            }
    },50);
});
​

jsFiddle

The small timeout is to make sure the mouse actually left both elements, rather than left one and entered another.

Upvotes: 8

Related Questions