Reputation: 73
I have some trouble showing/hiding this menu on mouse enter. I'd like the menu show when the mouse approaches the HEADER zone and stay up until the mouse leaves the zone.
The problem is when the mouse exits the page because the mouseleave function triggers and hide my menu (if the menu itself was not locked)
I set up a jsfiddle to explain better. http://jsfiddle.net/aZyz8/1/
<html>
<header>
<nav>
<ul>
<li><a href="#">Menu Item 1</a></li>
<li><a href="#">Menu Item 2</a></li>
<li><a href="#">Menu Item 3</a></li>
</ul>
</nav>
</header>
<div id="debug"></div>
</html>
CSS:
html {
background: grey;
height: 100%;
width: 100%;
}
header {
background: red;
height: 200px;
}
nav {
background: green;
width: 100%;
height: 50px;
position: absolute;
top: -50px;
}
li {
display: inline;
margin-left: 20px;
}
JS:
$('header').mouseenter(function() {
$('#debug').text('mouse enters header');
$('nav').animate({
top: '0'
});
}).mouseleave(function() {
$('#debug').text('mouse leaves header');
// if mouse does not leave window
$('nav').animate({
top: '-105px'
});
});
Does anybody have a clue on what do I have to do to trigger "mouse leaves page" to put in that IF? I tried almost everything both jQuery and plain Javascript side, using hover(), :hover and mouseover/mouseout but it seems it won't work on mouseout with html/body tags.
I also tried encapsulating that code to work only if mouse was hover html but of course when I hover "header" html loses :hover status breaking things anyway.
Thanks
Upvotes: 1
Views: 7276
Reputation: 11445
Check pageX and pageY of the event object to return if outside the bounds of the page.
$('header').mouseenter(function() {
$('#debug').text('mouse enters header');
$('nav').animate({
top: '0'
});
}).mouseleave(function(e) {
var pageX = e.pageX || e.clientX;
var pageY = e.pageY || e.clientY;
if (pageX < 0 || pageY < 0) { // don't execute the rest of this callback
return;
}
$('#debug').text('mouse leaves header');
// if mouse does not leave window
$('nav').animate({
top: '-105px'
});
});
Upvotes: 5
Reputation: 4075
If you want the menu to be visible while user moved cursor out of the window you can check mouse coordinates on mouseleave event.
$('header').mouseenter(function() {
$('#debug').text('mouse enters header');
$('nav').animate({
top: '0'
});
}).mouseleave(function(event) {
$('#debug').text('mouse leaves header');
// if mouse does not leave window
if (event.clientX <= 0 || event.clientY <= 0)
{
return;
}
$('nav').animate({
top: '-105px'
});
});
Here is an example.
Upvotes: 0