First, Id must be unique in the DOM. In this case, when you add multiple sets, switch to the class selector.
Then your variable number is local and overridden, and reset is 1 on each mousedown
var copydiv = $('.maindiv').clone(); var number = 1; // This was redefined and set as 1 on every `mousedown` // So make it global $("body").delegate(".imagediv","mousedown",function(event){ $(".maindiv").attr('class',"changedmain" + number); $(".imagediv").attr('class',"changedimage" + number ); copydiv.insertAfter("#appendafter"); // You might have to change this too // depending if this is repeated too number = number+1; }
Also, it is preferable to delegate the .on()
$("body").on("mousedown", ".imagediv", function(event){ $(".maindiv").attr('class',"changedmain" + number); $(".imagediv").attr('class',"changedimage" + number ); copydiv.insertAfter("#appendafter");
Decision:
The problem was using the method. Elements cloned using .clone() will contain a link, so instead of adding a new element, it will continue to update previously referenced objects.
Here is the solution:
var number = 1; //Our Counter Script function createDiv() { //Lets create a new div, // I mean WHY CLONE AT the first place?? // We are delegating events anyway :p $("<div />", { html : $('#maindiv').html(), // add the HTML of div we are trying to keep // ^ Better used cached // version is not updated regularly id : "maindiv-"+number // add the generate id number }).insertAfter("#appendafter"); // Now insert it number++; } $("body").on("mousedown", ".imagediv", function(event){ createDiv(); //Delegating on all elements with `imagediv` class });
Starx source share