Search code examples
javascriptjqueryonmouseover

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


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();
 });

Solution

  • 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