On clicking a link, a div is created which is draggable. I have another link which I want to be able to use to remove this newly created div.
Jquery code:
var counter = 0;
$(document).ready(function(){
$("#alphalink").click(function(){
var name = 'element'+ counter++;
$('#elementarea').prepend('<div id="' + name + '"></div>');
$("#" + name).prepend('<img id="theImg" src="http://us.metamath.org/symbols/alpha.png" />');
$("#" + name).css("z-index", counter);
$("#" + name).css("position", "absolute");
$("#" + name).draggable({ cursor: "move"});
});
$("#cleardiv").click(function(){
var olddiv= 'element'+ counter;
alert(olddiv);
$("#element" + counter).remove();
});
});
HTML code:
<div id="elementarea" style="width:300px; height:200px; background-color:#ccc; margin-top:10px; margin-right: 15px; float:left ">
<p>Staging area here</p>
</div>
<div id ="alphalink">
<p> Alpha Click </p>
</div>
<div id ="cleardiv">
<p> clear item </p>
</div>
On clicking on “Alpha Link”, a draggable div is created. On clicking “clear item”,the div should be removed.
However, the jquery .remove() does not seem to remove this newly created div. What is going wrong in this example?
You can try out the entire code here – http://jsbin.com/iboxoy/95/edit#source
The problem is here:
The postfix increment
counter++operator returns old value to be used as a result of expression, and than increments the variable, so you end up with div, with id 0, butcountervalue is 1. Try replacing with prefix increment++counter.Also, it would be a good idea to keep those created divs in an array so you can always access all of them: