sveti petar
sveti petar

Reputation: 3797

jQuery - call function onmouseout but only if the cursor wasn't moved to a certain area

I have this link:

<a class='itemshow'>Show Details</a>

When this link is hovered over, a div opens up below it with some content. That works fine. Now, I need a .mouseout() event which closes the div that was opened (div's id is gen_details) but ONLY if the cursor wasn't moved down to the div itself.

I have written a function which closes the div (see below, slideToggle does it), I just need a modification - a condition that checks whether the cursor is within the div's boundaries, and only executes the code if it's not.

    $('a.itemshow').mouseleave(function()
        { 
//if(condition here to check if cursor is out of the div's boundaries){
        if($('#gen_details').hasClass("open")){
            $('#gen_details').slideToggle(300);
            $('#gen_details').removeClass("open");
                return false;
            }
//}
        });

Shouldn't be too complex but I can't figure out how to do it without any complicated hacks.

Upvotes: 0

Views: 403

Answers (2)

Avukonke Peter
Avukonke Peter

Reputation: 121

No need for timers or anything like that. You just set the mouseover function to select both the link as well as the div. So if you are hovering over your containing div it does the default action and move away from the div or link then the mouseout handler is called, not sure you get what I mean.

Fiddle: http://jsfiddle.net/avukonke/fcSUH/

<a href="www.twitter.com" class="tester"><img src="https://blog.twitter.com/sites/all/themes/gazebo/img/twitter-bird-white-on-blue.png" /></a>

<div style="width:200px; height: 100px; background-color:black; clear:none;" class="myblock"></div>

Upvotes: 0

adeneo
adeneo

Reputation: 318342

This sort of thing is usually solved with a small timeout that's cleared if the mouse enters a certain element. Something like:

var timer;

$('a.itemshow, #gen_details').on({
    mouseenter: function() {
        clearTimeout(timer);
        $("#gen_details").slideDown(300);
    },
    mouseleave: function() {
        timer = setTimeout(hideGen, 200);  
    }
});

function hideGen() {
    $("#gen_details").slideUp(300);
}

FIDDLE

Upvotes: 1

Related Questions