Michael Schwartz
Michael Schwartz

Reputation: 8425

Can't Drag Dynamically Appended DIV

http://liveweave.com/rh0ILM

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

Answers (3)

Saranya Sadhasivam
Saranya Sadhasivam

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

Harry
Harry

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
    });
}));

Working Demo

Upvotes: 3

Pan Wangperawong
Pan Wangperawong

Reputation: 1250

Since this div is newly added to the DOM, in $("#divgen").click(....) you need to rerun the drag function.

Upvotes: 0

Related Questions