Code :
HTML
<a id="go" href="javascript:void(0);">Start</a>
<div id="container">
<div class="example" id="example1">1</div>
<div class="example" id="example2">2</div>
<div class="example" id="example3">3</div>
</div>
jQuery
$('#go').click(function () {
InitDragDrop();
});
function InitDragDrop() {
var BoxImmagineFutura = null;
$('#boxTemp').remove();
BoxImmagineFutura = $('<div/>', { id: 'boxTemp', class: 'boxTempClass', text: 'Added' });
BoxImmagineFutura.appendTo($("#container"));
$('.example').mousedown(function (e) {
BoxImmagineFutura.insertBefore("#example2");
BoxImmagineFutura.show();
});
}
CSS
.example, #boxTemp
{
float:left;
width:40px;
height:40px;
margin:10px;
border:1px solid #000000;
cursor:pointer;
}
#boxTemp
{
background-color:red;
display:none;
}
In order :
- Click Start to initialize function/handlers;
- Click on a div (you will show the Added box when you are pressing the mouse);
- Click Start again to reset all variables;
- Than click again on a div : WHY there are two Added div? I’ve removed the previous one with
$('#boxTemp').remove();
Can you help me to resolve this trouble? If I remove BoxImmagineFutura.insertBefore("#example2"); there isn’t "clonation" of that div.
FIRST EDIT :
Yeah, every time I call InitDragDrop() I should also unbind mousedown(), but this doesn’t explain my problem
Pull your
var BoxImmagineFutura = null;out of your function. Also, you don’t needBoxImmagineFutura.appendTo($("#container"));as yourinsertBeforehandles inserting it into the DOM.jsFiddle example