I would like to move some html elements from one container to another endlessly using jQuery append
function but, the click event won't fire no more when I click on the element/s that have been appended.
Based on some threads similar to mine I found out that appended elements are stripped off of their event listeners. How can I avoid that, can someone show a solution ?
Here is the: Fiddle
$('section.container-A div.elem').click(function() {
$('section.container-B').append(this) ;
}) ;
$('section.container-B div.elem').click(function() {
$('section.container-A').append(this) ;
}) ;
jQuery click not working at the time page loading, jQuery Onclick Method is tried to an element or selector. As a result, the binding will fail if the element we wish to click isn't present when the page is ready.
The Element.append() method inserts a set of Node objects or string objects after the last child of the Element . String objects are inserted as equivalent Text nodes.
As much as they both can be used interchangeably, there are a few subtle differences between the two methods. The append method is used to insert either Node objects or DOMStrings (basically a string or text) into the DOM, while the appendChild method can only be used to insert Node objects into the DOM.
It will work. Use the following method for appended.
$(document).on('click', 'section.container-A div.elem', function() {
$('section.container-B').append(this) ;
}) ;
Explanation of the problem,
Doing the following,
$("span").click(function(){
An event handler is attached to all span
elements that are currently on the page, while loading the page. You create new elements with every click. They have no handler attached. You can use
$(document).on('click', 'span.class', function(...
That will handle the clicks on the new elements as well.
You need to use the .on()
method:
$(document).on('click', 'section.container-1 div.elem', function() {
var html = this;
$('section.container-2').append(html) ;
}) ;
$(document).on('click', 'section.container-2 div.elem', function() {
var html = this;
$('section.container-1').append(html) ;
}) ;
Fiddle: http://jsfiddle.net/x2A7n/16/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With