PiotrS
PiotrS

Reputation: 157

Mouseover Mouseout with overlapping content

When I mouseover the div with class=background (the little green square in the demo) I fade in the div with class=hover (displaying the grey and blue divs in the demo).

The grey partially overlaps the .background and I can move the mouse around inside it without triggering the mouseout on .background.

But..

If I move the mouse outside the grey div (to hover over the blue for example) then the mouseout on .background gets triggered.

How can I prevent this from happening so that as long as I am hovering over the newly displayed .hover div the mouseout on '.background' will not be triggered?

$('.AddDiv').on('click', function() {
  var html = '<div class="container"><div class="background"></div><div class="hover"></div></div>';
  $('.Wrap').prepend(html);
});

$(".Wrap").on("mouseover", ".background", function() {
  $(this).next(".hover").fadeIn(500);
});

$(".Wrap").on("mouseout", ".hover", function() {
  $(this).fadeOut(200);
});
.Wrap {
  width: 650px;
  height: 800px;
}
.container {
  position: relative;
  top: 5px;
  left: 5px;
  width: 200px;
  height: 200px;
  background-color: red;
  float: left;
  margin-left: 5px;
  margin-top: 5px;
}
.AddDiv {
  position: absolute;
  top: 0px;
}
.background {
  width: 20px;
  height: 20px;
  background-color: green;
  position: absolute;
  left: 170px;
  top: 10px;
}
.content {
  width: 170px;
  height: 120px;
  background-color: grey;
  position: relative;
  left: 15px;
  top: 15px;
}
.navigation {
  width: 190px;
  height: 40px;
  background-color: blue;
  position: relative;
  top: 30px;
  left: 5px;
}
.hover {
  width: 200px;
  height: 200px;
  background-color: rgba(255, 255, 255, 0.8);
  position: absolute;
  z-index: 1001;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Wrap">
  <div class="container">
    <div class="background"></div>
    <div class="hover">
      <div class="content"></div>
      <div class="navigation"></div>
    </div>
  </div>
</div>
<button class=AddDiv>AddDiv</button>

Upvotes: 0

Views: 1038

Answers (1)

Banzay
Banzay

Reputation: 9470

Use mouseleave instead of mouseout:

$('.AddDiv').on('click', function() {
    $('.Wrap').prepend($('<div class="container"><div class="background"></div><div class="hover"></div></div>'));
});

$(".Wrap").on("mouseover", ".background", function () {
    $(this).next(".hover").fadeIn(500);
});


$(".Wrap").on("mouseleave", ".hover", function () {
$(this).fadeOut(200);
});

Upvotes: 2

Related Questions