Tom Tom - 29 days ago 6
CSS Question

How to show/hide box on mouseleave?

What is the simplest way to do the following?


  1. When user moves his mouse over the red box- the green box appears

  2. If user moves his cursor from red to green box- the green box doesn't disappear

  3. When user moves his cursor away from the green box (and not back to the red box)- the green box vanishes.



The red box doesn't touch the green box- like on the picture.

Illustration

Here's what I tried but that doesn't solve the problem:

$('#red').mouseenter(function()
{
$('#green').show();
});
$('#green').mouseleave(function()
{
$('#green').hide();
});


The problem here is that the green box vanishes once you move your cursor from red one.

Answer

I think you are trying to make this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>

    <style media="screen">
        .red {
            width: 200px;
            height: 200px;
            background-color: red;
        }
        .green {
            display: none;
            width: 200px;
            height: 200px;
            background-color: green;
        }
        .divider {
            height: 200px;
        }
    </style>

</head>
<body>

    <div class="red"></div>
    <div class="divider"></div>
    <div class="green"></div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <script type="text/javascript">

        $(document).ready(function(){

            $(".red").mouseenter(function(){
                $(".green").show();
            });
            $(".green").mouseleave(function(){
                $(".green").hide();
            });

        });

    </script>

</body>
</html>