Why doesn't click work on appended elements?

user9349193413 picture user9349193413 · Aug 9, 2013 · Viewed 12.3k times · Source

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) ;
    }) ;

Answer

Optimus Prime picture Optimus Prime · Aug 9, 2013

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.