0

I am creating a clone of a div, but unfortunately i am not able to add event listener to cloned div.

I tried using clone(true,true) but still did not get it running.

Can some one help me out with it please

JS fiddle for clone

Clicking image next to And, adds a new div

Code i tried for adding event listener

$("#add").on('click',function () {
    $("#cont").clone(true, true).appendTo(".container");

});
5
  • 4
    Beware of duplicate IDs! Commented Apr 10, 2014 at 12:51
  • 2
    @Sandy: live is deprecated in newer version of jQuery Commented Apr 10, 2014 at 12:51
  • 2
    @Sandy .live() is deprecated Commented Apr 10, 2014 at 12:51
  • 1
    The problem that you're running into is that you're cloning and appending items that have the same id. As you know, id's must be unique in a web page or you'll get funny results. Make sure to modify the id of the appended item so that each appended item gets a unique id. Commented Apr 10, 2014 at 12:51
  • How do i change Id dynamically??? And as you can see click event is assigned to ID, now if i change id of cloned div how will click function work??? Commented Apr 10, 2014 at 12:52

1 Answer 1

3

First you should change your cont id to a class as multiple ids are bad and won't work properly.

Second, use jQuery's first method to grab the first in the returned jQuery nodelist that you get from grabbing all the cont classes: $('.cont') and then clone the node. You have to grab only the first one or you'll end up adding multiples of the div back on to the page.

$(".cont").first().clone(true, true).appendTo(".container");

Third, change the delete id to a class.

Fourth, because you're adding to the DOM you need to use event delegation on the parent node in order to catch the events properly. Use closest to find the nearest cont class and remove it.

$('.container').on('click', '.delete', function () {
    $(this).closest('.cont').hide();
});

Fiddle

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.