How to make showed div stay unhidden on hover?

Viewed 42

I have a jquery function that on hover it shows a hidden div to the side and it works fine. What I wanted to add is when I hover to the showed div ie box2 the div disappears therefore I can't interact with box2 how can I make box 2 stay unhidden when I hover on it then on hover out it fades out again. I can do this easily with vanilla javascript but I need the jquery fade effect so how can I accomplish it with jquery. Any help is appreciated. Thanks in advance.

$("#box1").hover(function(){
    $("#box2").fadeIn("slow");
},
function(){
    $("#box2").fadeOut();
});
.box1 {
  position: absolute;
  left: 4%;
  width: 20%;
  height: 10%;
  background-color: black;
}

.box2 {
  position: absolute;
  left: 24%;
  width: 20%;
  height: 30%;
  background-color: grey;
  display:none;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<div class="box1" id="box1"></div>
<div class="box2" id="box2"></div>

2 Answers

Here are 2 ways to handle it. The one that is commented out will keep box 2 visible until you mouse out of box 2.

The other one (uncommented) will set a short timer and test to see if you're still overing over box 2. I think that's the one you're looking for.

let ontarget = false
$("#box1, #box2").hover(function(e) {
    $("#box2").fadeIn("slow");
    ontarget = e.target.id == 'box2'
  },
  function(e) {
    // keep open unless mouse out of box 2
    //if (e.target.id != 'box1') $("#box2").fadeOut();

    // after a short delay (100 ms) test to see if we're still over box2, if so do nothing.
    // though if we mouse out it will rerun this if statement to close it like you expect
    setTimeout(() => {
      if (!ontarget || e.target.id == 'box2') $("#box2").fadeOut();
      if (e.target.id == 'box2') ontarget = false
    }, 100)

  });
.box1 {
  position: absolute;
  left: 4%;
  width: 20%;
  height: 10%;
  background-color: black;
}

.box2 {
  position: absolute;
  left: 24%;
  width: 20%;
  height: 30%;
  background-color: grey;
  display: none;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<div class="box1" id="box1"></div>
<div class="box2" id="box2"></div>

You have a couple of options here. First, you could wrap both boxes in a <div>, and just modify the jquery code to show the div on hover.

Another option could be to use the css !important attribute (it is bad habit, however) to add another style rule to show it. This would look as follows:

.box2:hover {
     display:block;
}

Feel free to comment with any questions! Good Luck!

Related