Aakash Thakur Aakash Thakur - 3 months ago 15
CSS Question

Hold a div panel when the mouse is over it

I have been working on a div that shows on mousemove and hides after a certain delay. I have achieved the aforementioned thing.

I have attached the code below-



var nav = $('.nav');
var movementTimer = null;

var $doc = $(document);


$doc.on('mousemove', function(e) {
nav.addClass('show');
});

$doc.on('mousemove', function(e) {
clearTimeout(movementTimer);
movementTimer = setTimeout(function() {
nav.removeClass("show");
}, 500);
})

.nav {
background: #111;
text-align: center;
color: #fff;
padding-top: 20px;
padding-bottom: 20px;
position: fixed;
right: 0px;
bottom: -100px;
left: 0px;
transition: .4s ease-in-out;
}
.nav.show {
bottom: 0px;
transition: .2s ease-in-out;
}

<div class="nav">This is a funny nav</div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="jquery.unevent.js"></script>





http://jsfiddle.net/wVVbT/129/

According to this code, the div goes away after certain time.

Now the question that I have is how to hold the div when I hover or mouse over it.
Help would be much appreciated.

Answer

Simply check if target element (under e.target) has class nav

Check out this fiddle:

var nav = $('.nav');
var movementTimer = null;

var $doc = $(document);


$doc.on('mousemove', function(e) {
nav.addClass('show');    
});

$doc.on('mousemove', function(e)
    {
        clearTimeout(movementTimer);
        if(!$(e.target).hasClass("nav")) {
            movementTimer = setTimeout(function()
            {
                nav.removeClass("show");
            }, 500);
        }
    })
body {
  font-family: helvetica neue, helvetica, arial, sans-serif;
  height: 8000px;
}


.nav {
  background: #111;
  text-align: center;
  color: #fff;
  padding-top: 20px;
  padding-bottom: 20px;
  position: fixed;
  right: 0px;
  bottom: -100px;
  left: 0px; 
  transition:.4s ease-in-out;
}

.nav.show{
  bottom:0px;
  transition:.2s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">This is a funny nav</div>     
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="jquery.unevent.js"></script>

There is a function .hasClass(class) that returns true if element has provided class. So simply insert an if statement that check is element has not class nav and execute timer.