How to make toggle off when on mouse over is done?

5.2k views Asked by At

I have created an element that is displayed when I am over a particular box.

If I move my mouse over the box I can see my element but then I need to move my mouse in and out twice for the element to disappear. How can I fix it? Shouldn't the element hide itself once I move the mouse out?

How do I make my box only show when mouse is over the box?

<script>
$("#box").on("mouseover",function()
{                  
   $("#my-box").toggle();
});
</script>

I tried to hide it myself, but it didn't work:

 $("#box").on("onmouseout", function()
 {
     $("#my-box").hide();
 });
4

There are 4 answers

2
Guruprasad J Rao On BEST ANSWER

You can use mouseover and mouseout in a same eventlistener like one below:

$("#box").on("mouseover mouseout",function()
{                  
   $("#my-box").toggle();
});
#my-box{
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
    Box here
</div>
<div id="my-box">
    My Box
</div>

FIDDLE DEMO

0
Bhojendra Rauniyar On

The problem with your code is you're using onmouseout instead of use mouseenter and mouseleave method.

You can use hover:

$('#box').hover(function(){
   $('#my-box').toggle();
});
0
Dhaval Marthak On

You can use combination of both

$("#box").mouseover(function() {
    $("#my-box").show();
}).mouseout(function() {
    $("#my-box").hide();
});

Example

0
oshell On

jQuery Solution

HTML

<div class="box" id="action"></div>
<div class="box" id="hidden"></div>

JS

$("#action").on("mouseover mouseout",function()
{
    $("#hidden").toggle();
});

CSS

.box{
    width: 30px;
    height: 30px;
    background: red;
    margin: 10px;
}

#hidden{
    display: none;
}

JSFiddle

Allthough it would be better doing this by just using CSS.

CSS Only Solution

.box{
    width: 30px;
    height: 30px;
    background: red;
    margin: 10px;
}

#action:hover + #hidden{
    display: block;
}

#hidden{
    display: none;
}

JSFiddle