Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't click work on appended elements?

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) ;
    }) ;
like image 201
user9349193413 Avatar asked Aug 09 '13 18:08

user9349193413


People also ask

Why click function is not working in jQuery?

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.

What does append() do in javascript?

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.

What is the difference between append()` and appendChild?

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.


2 Answers

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.

like image 110
Optimus Prime Avatar answered Sep 29 '22 22:09

Optimus Prime


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/

like image 36
Willem Ellis Avatar answered Sep 29 '22 22:09

Willem Ellis