'Cloning elements with their events not working
I am cloning a div using jQuery and find that events on cloned elements do not work although they work on the original elements. How can I go about this? Note how the answer in the question states that...
"This is how jQuery's clone() method is able to copy a node with its event listeners, for example"
let add = document.getElementsByClassName("add"),
rem = document.getElementsByClassName("rem"),
container = document.getElementsByClassName('container')[0];
for (let i = 0; i < add.length; i++) {
add[i].addEventListener("click", () => {
$(".cloneable").clone(true, true).appendTo(".container");
});
}
for (let i = 0; i < rem.length; i++) {
rem[i].addEventListener("click", () => {
if (container.childElementCount > 1) {
$(".cloneable:last").remove();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="cloneable">
<div>
<a class="btn btn-primary add" role="button">Add cell</a>
<a class="btn btn-primary rem" role="button">Remove cell</a>
</div>
<iframe src="index.php"></iframe>
</div>
</div>
Solution 1:[1]
ETA: This code clones all elements named ".cloneable", so on second click it creates TWO clones, and so on. You should clone with $('.cloneable:first') or similar.
The issue seems to arise from you binding javascript native events. Using jQuery Events solves your problem.
let add = document.getElementsByClassName("add"),
rem = document.getElementsByClassName("rem"),
container = document.getElementsByClassName('container')[0];
for (let i = 0; i < add.length; i++) {
$(add[i]).on("click", () => {
$(".cloneable:first").clone(true, true).appendTo(".container");
});
}
for (let i = 0; i < rem.length; i++) {
$(rem[i]).on("click", () => {
if (container.childElementCount > 1) {
$(".cloneable:last").remove();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="cloneable">
<div>
<a class="btn btn-primary add" role="button">Add cell</a>
<a class="btn btn-primary rem" role="button">Remove cell</a>
</div>
<iframe src="index.php"></iframe>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lalalena |
