PiotrS PiotrS - 1 month ago 8
CSS Question

Function prepend() jquery hover and counter click

I have a little problem with

prepend()
because if I "copy" my div and if click on counter the count change in whole divs the same is with hover. Is this possible change number count and hover only in clicked or hovered div?

Thank you for help and time:)

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>


And javascript

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

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


FIDDLE

Answer

Here we are creating dynamic id for each prepend. And by sending that div id to the javascript function and using same count logic as @Zakaria Acharki used to maintain count value.

var divNumber = 1;
$('.AddDiv').on('click', function() {
    $('.Wrap').prepend($('<div class="container"><div class="count" id="div'+divNumber+'" onclick="makeCount(this.id);">My Counter</div><div class="background"></div><div class="hover"></div></div>'));
  divNumber++;
});

function makeCount(id){
  var count = parseInt( $("#"+id).text());
  if( isNaN(count) ){
    count = 1; //For the first click
  }else{
    count++;
  }

  $("#"+id).text(count);
}

$(".background").on("mouseover", function() {
    $(".hover").fadeIn(500);
});
$(".hover").on("mouseout", function() {
    $(".hover").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;
}
.count
{
  position:absolute;
  width:100px;
  height:100px;
  position:absolute;
  left:50%;
  top:50%;
  margin-left:-50px;
  margin-top:-50px;
  background-color:white;
  text-align:center;
  line-height:100px;
  cursor:pointer;  
}
.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="count" id="div0" onclick="makeCount(this.id);">My Counter</div>
        <div class="background"></div>
        <div class="hover"></div> 
    </div>
</div>
<button class=AddDiv>AddDiv</button>

Comments