Jquery Drag And Drop On Ajax Loaded Div
Solution 1:
This appends because you try to call the droppable
on a non-existing element at that moment. To solve this, you could use the callback function that can be attached to the load
function and run the rest after that.
$(document).ready(function(){
$("#site-preview").load("/site/preview", function() {
// Page loaded and injected// We launch the rest of the code
$( ".draggable" ).draggable({
helper:'clone',
appendTo: 'body',
scroll: false
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" ).find( "p" ).html( "Dropped!" );
}
});
});
});
You can find other information about the load
function here. The callback can take arguments and can be used, for example to check if it's a 404 or not.
Solution 2:
Well I was able to get it to work by adding the draggable/droppable code to the ajax loaded div itself. So the above would be amended like so
ajax loaded code
<divclass="droppable col-md-2"style="height:100px;border:1px solid gray"><p></p></div><script>
$(function() {
$( ".draggable" ).draggable({
helper:'clone',
appendTo: 'body',
scroll: false//stops scrolling container when moved outside boundaries
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" ).find( "p" ).html( "Dropped!" );
}
});
});
</script>
And those script lines would be taken out of the main page
Solution 3:
Ajax is Asynchronous. So if you call some ajax and then call some other command, the ajax will usually finish afterwards.
This is where callbacks are useful. Try adding a callback to the ajax load
call as shown here: http://api.jquery.com/load/
Something like:
$( "#site-preview" ).load( "/site/preview", function(){
$( ".droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" ).find( "p" ).html( "Dropped!" );
}
});
});
Side note: you should probably start using scripts instead of <script>
tags.
Post a Comment for "Jquery Drag And Drop On Ajax Loaded Div"