CommanderData
CommanderData

Reputation: 583

Keeping div open after hovering an element

I have some trouble with jquery / css. When hovering over a link, I want to show a box, but this box mustn't disappear while moving the cursor from the link to the box. At the moment this works but another thing is, that the box also should be closed if you move the cursor from the link to any other part of the site which is not the box.

This fiddle demonstrates this behaviour. Just move the cursor from the link to some other place on the site (but avoid hovering the appearing box) and you will see, that the box is still there.

This is what my jQuery code looks like:

$("#link").mouseenter(function () {
    $("#cart_box").fadeIn();
});
$("#cart_box").mouseleave(function() { 
    $("#cart_box").fadeOut();
});

Upvotes: 0

Views: 1269

Answers (3)

Pevara
Pevara

Reputation: 14310

You do not need javascript for this. You should simply include your 'box' inside the a and display it on hover of the link. Something like this:

HTML:

<a>
    hover me
    <div>to see me</div>
</a>

CSS (unprefixed!):

a div {
    transform: scale(0);
    opacity: 0;
    transition: all .5s;
}
a:hover div {
    transform: scale(1);
    opacity: 1;
}

I added a transition / transform to illustrate that these simple things can easily be done with pure css, and are often a lot smoother and faster.

See for yourself: http://jsfiddle.net/6gT2u/

Upvotes: 0

gaurav5430
gaurav5430

Reputation: 13882

include your cart_box inside the a,

<div id="left"> 
    <a href="#" id="link">
        <div style="margin-left: 31px;">
            <div class="cart_img">IMG</div>
            <span style="margin-left: 10px;">My Cart</span> 
        </div>
        <div id="cart_box">

    </div>
    </a>

</div>

then change your functions like this

$("#link").mouseenter(function () {
    $("#cart_box").fadeIn();
});
$("#link").mouseleave(function() { 
    $("#cart_box").fadeOut();
});

but keep in mind, by default a will be a inline element, so when the box is visible and you try to hover into the box, it might flicker, as you are moving out of a for 1px maybe and then moving in, to avoid that you need to add some height to a, equal to the gap between the cart_box top and the IMG bottom , for that you would need your a to be block, add this css to your a

#left a{
    display:block;
    height:50px; //anything to cover the 1px or 2px between cart_box top and the IMG bottom
}

also,see the updated fiddle: http://jsfiddle.net/a5TLC/7/

P.S: you may want to change the width of your cart_box, once you have it inside the link.

Upvotes: 1

diutsu
diutsu

Reputation: 103

Just encapsulate the link and the box on a div, and apply the mouseleave to that div.

This happens because the mouseleave event cannot be called if the mouse doesn't enter the box.

Upvotes: 0

Related Questions