What can I fix so that the method .draggable()
is applied correctly to elements created using the add button?
$(document).ready(function() {
$('.drag_drop').draggable({
addClasses: false,
containment: "parent"
});
$('#add').click(function(){
$('.parent').append('<div class="drag_drop">Aquí <b>no</b> funciona</div>')
});
});
.parent {
width: auto;
height: 100px;
border: 1px black solid;
}
.drag_drop {
font-family: Arial;
text-align: center;
width: 80px;
height: 80px;
border: 1px black solid;
float: left;
margin: 5px 5px 5px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div class="parent">
<div class="drag_drop">
Aquí funciona
</div>
</div>
<br />
<button id="add" type="button">Añadir</button>
This happens because the drag function is set to run only once when the document is ready. Therefore, when you add a new node to the document, it will not be applied to the new element.
For this, you would have to apply a "live" check for new elements implemented in the document and then apply lo
.draggable()
, which you could do with a.on("DOMNodeInserted ", function ()
but we're not going to go that route because that's a bumpy and sensible road for each project.For this exact example in your question we can wrap the
.draggable()
in a function, and call it when there is a click on the button.When the browser interprets the entire page for the first time, a DOM tree is created of all the elements that are at that moment (that is why your first element works since it has been there since the page was created).
Now, JQuery creates a virtual DOM of the page and this is not modified unless you refresh, so even if you see that the boxes appear, they do not exist in the DOM and therefore the class you put cannot be applied to them.
What can be done? The short answer is called 'Event Propagation' and it consists of telling the parent of these elements, which also exists from the beginning, that every time a child is added to it, it tells it that it must belong to that class.
In your example it would be something like this: