PiotrS PiotrS - 28 days ago 15
Javascript Question

Hover in prepend() function

HTML:

<div class="Wrap">
<div class="container">
<div class="count">My Counter</div>
<div class="background"></div>
<div class="hover"></div>
</div>
</div>
<button class="AddDiv">AddDiv</button>


jQuery:

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

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

$(".hover").on("mouseout", function () {
$(".hover").fadeOut(200);
});


https://jsfiddle.net/mpd075s8/5/

Hello, I have problem with hover, look at the jsfiddle and click on button AddDiv and when hover on the green square hovered are all divs, but I would like that every div will be hovered separately. And hover doesn't work in new divs

Answer

Two things

  1. You need to use delegated event for dynamic element

  2. Use this for the reference of current element.

Try like following.

$('.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("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;
}

.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>
  </div>
</div>
<button class=AddDiv>AddDiv</button>

Comments