I am faced with the problem of wanting to have a behavior defined for a configuration object and apply it to all the elements of the selected class, even those that are subsequently generated in the DOM .
For events, there is a practical way to do it by hooking the event to document
and passing on()
the element that we want the function to fire as the second parameter of the function. But I can't find a similar way to do it and what I'm trying to avoid is initializing it inside crear_cubo()
my example function.
Would there be a way to do it?
$(function () {
$('.cubo').draggable({
revert: true
});
$(document).on('click', '#crear-cubo', crear_cubo);
});
function crear_cubo () {
let contenedor = $('#contenedor-cubos');
let html = '<div class="cubo"></div>';
contenedor.append(html);
}
#contenedor-cubos {
display: flex;
flex-wrap: wrap;
padding: 10px 0;
}
.cubo {
width: 100px;
height: 100px;
background-color: red;
border: 2px solid black;
float: left;
margin-right: 5px;
}
.inicial {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous"></script>
<div id="contenedor-cubos">
<div class="cubo inicial"></div>
</div>
<button type="button" id="crear-cubo">Crear cubo</button>
You should listen for changes to the document or container to detect when elements are added and you can use the arrive.js library .
If they are only going to appear in a specific container, listen for changes there and not in the document, to prevent the browser from doing extra work. In fact, this also applies to clicks, there is no point delegating them to the document if they are unique elements.