StacyMidget StacyMidget - 4 months ago 9
Javascript Question

Hover on div triggers div that will stay if hovered on

I have this div that when it's hovered on, it will activate this other div. When the user moves his mouse on the activated div, I want that div to stay. Here is a snippet.

When you hover on the gold box, the purple box hides and the grey box is shown. Instead of disappearing, I want the grey box to stay when the mouse is over the grey box. And then when the mouse hovers over the gold box the second time, the grey box will hide itself, and the purple will return. How can I do this with smooth animations in Jquery?



$(function() {
$("#startMenu").hide();
var timeoutId;
$("#menuDesktop").hover(function() {
if (!timeoutId) {
timeoutId = window.setTimeout(function() {
timeoutId = null;
$("#topBarDesktop").slideUp('400');
$("#startMenu").slideDown('1000');
}, 400);
}
},
function() {
if (timeoutId) {
window.clearTimeout(timeoutId);
timeoutId = null;

} else {
$("#startMenu").slideUp('slow');
$("#topBarDesktop").slideDown('400');
}
});
});

#topBarDesktop {
position: fixed;
top: -.1em;
right: -1em;
padding: 20px 100%;
background: purple;
}
#menuDesktop {
width: 50px;
position: absolute;
height: 50px;
background: gold;
display: inline-block;
vertical-align: top;
float: left;
left: -15px;
top: -15px;
}
#menuDesktop:hover {
background: red;
}
#startMenu {
background: grey;
padding: 100% 100%;
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="topBarDesktop">

</div>
<div id="menuDesktop">

</div>
<div id="startMenu">

</div>




Answer

You can change your else to and else if in order to check if #startMenu is hovered on or not. Then you'd also just want to make sure to call .hover() on both #menuDesktop and #startMenu, so that things slide back into place when you hover off of #startMenu as well.

$("#menuDesktop, #startMenu").hover(function() { //Added #startMenu to selector
  if (!timeoutId) {
    timeoutId = window.setTimeout(function() {
      timeoutId = null;
      $("#topBarDesktop").slideUp('400');
      $("#startMenu").slideDown('1000');
    }, 400);
  }
}, function() {
  if (timeoutId) {
    window.clearTimeout(timeoutId);
    timeoutId = null;
  } else if ($("#startMenu:not(:hover)").length && $("#menuDesktop:not(:hover)").length) { //Checks that neither #startMenu or #menuDesktop is hovered on.
    $("#startMenu").slideUp('slow');
    $("#topBarDesktop").slideDown('400');
  }
});

Check out this working fiddle