Reputation: 8425
http://jsbin.com/IZodOSU/1/edit
All divs with the drag class should be draggable, but when one is appended it's not draggable. Can anyone help me out with this?
HTML
<script src="http://threedubmedia.com/inc/js/jquery-1.7.2.js"></script>
<script src="http://threedubmedia.com/inc/js/jquery.event.drag-2.2.js"></script>
<script src="http://threedubmedia.com/inc/js/jquery.event.drag.live-2.2.js"></script>
<button id="divgen">Gen Div</button>
<div class="container">
<div class="drag" style="left:20px;"></div>
<div class="drag" style="left:100px;"></div>
<div class="drag" style="left:180px;"></div>
</div>
CSS
.drag {
position: absolute;
border: 1px solid #89B;
background: #BCE;
height: 58px;
width: 58px;
cursor: move;
top: 120px;
}
JS/JQuery
jQuery(function($){
$('.drag').drag(function( ev, dd ){
$( this ).css({
top: dd.offsetY,
left: dd.offsetX
});
});
$("#divgen").click(function() {
$("div.container").append('<div id="whatever" class="drag">my div</div>');
});
});
Upvotes: 0
Views: 1388
Reputation: 1294
Call the drag function once again after a new div is appended.
jQuery(function($){
$('.drag').drag(function( ev, dd ){
$( this ).css({
top: dd.offsetY,
left: dd.offsetX
});
});
$("#divgen").click(function() {
$("div.container").append('<div id="whatever" class="drag">my div</div>');
$('.drag').drag(); // Call drag function.
});
});
Upvotes: 0
Reputation: 89780
Try the below. You have to use delegation since the DIV is dynamically created.
$('.container').on('drag','.drag',(function( ev, dd ){
$( this ).css({
top: dd.offsetY,
left: dd.offsetX
});
}));
Upvotes: 3
Reputation: 1250
Since this div is newly added to the DOM, in $("#divgen").click(....) you need to rerun the drag function.
Upvotes: 0