Reputation: 147
When I click and append a new div call block2, the draggable drag & stop not work?
How to fix it??
DEMO: http://jsfiddle.net/hbGkN/1/
HTML
<div id="btn"><input name="click" type="button" value="Click" /></div>
<div class="block1" style=" width:100px; height:100px; background:orange;">I am Block1</div>
JS
$('#btn').click(function(){
var $newDiv=$('<div class="block2" style=" width:100px; height:100px; background:green;">I am Block2</div>');
$( "#btn").parent().append($newDiv);
});
$('.block1').draggable({
drag: function() {
$('.block1').text('Drag Now!');
},
stop: function() {
$('.block1').text('Stop Now!');
}
});
$('.block2').draggable({
drag: function() {
$('.block2').text('Drag Now!');
},
stop: function() {
$('.block2').text('Stop Now!');
}
});
Upvotes: 1
Views: 1604
Reputation: 2365
A much more cleaner solution is to call the function draggable after the append is done.
$('#btn').click(function(){
var newDiv = $('<div class="block2" >Block2</div>');
$(newDiv).appendTo($(this).parent());
$('.block2').draggable();
});
this way you have all the function drag and stop applied to it after it goest live.
Upvotes: 1
Reputation: 6366
The issue is the appended DOM element isn't 'live' when you add it so has never had the draggable
methods applied to it. This code serves the purpose well.
function drag(e) {
$(e.target).text('Drag Now!');
}
function stop(e) {
$(e.target).text('Stop Now!');
}
$('#btn').click(function(){
var newDiv = $('<div class="block2" style=" width:100px; height:100px; background:green;">I am Block2</div>');
$(newDiv).appendTo($(this).parent()).draggable({drag: drag, stop: stop});
});
$('.block1').draggable({drag: drag, stop: stop});
Since your drag
and drop
methods are identical it makes more sense to reuse them.
Upvotes: 0
Reputation: 9869
You should try this, because, 'block2' class div is not present in dom, So the code will not able to add draggable to it. So, after adding 'block2'to DOM, you should call the draggable on it. Then It will work as you aspect.
$('#btn').click(function(){
var $newDiv=$('<div class="block2" style=" width:100px; height:100px; background:green;">I am Block2</div>');
$( "#btn").parent().append($newDiv);
$('.block2').draggable({
drag: function() {
$('.block2').text('Drag Now!');
},
stop: function() {
$('.block2').text('Stop Now!');
}
});
});
CHECK this DEMO
Upvotes: 3