0

Using jQuery 1.10 I'm cloning a div containing a button on which a click event is defined. The div gets cloned but not the click event.

I've seen this question asked many times (for example: Click action from cloned element does not work ) and all answers suggest to use clone(true) or clone(true, true).

This does not seem to work in this case.

I've made a small working example: (FIDDLE LINK: http://jsfiddle.net/wD3dq/1/ )

HTML:

<html>
<body>
    <a href=# " id="clickMe">Click Me to add a new Div</a>
    <div id="elementHolder">
        <div id="webThumb5">
            <p>Test1 <a href="# " class="del_button " role="button ">Delete</a></p>
        </div>
        <div id="webThumb6">
            <p>Test2 <a href="# " class="del_button " role="button ">Delete</a></p>
        </div>
        <div id="webThumb7">
            <p>Test3 <a href="# " class="del_button " role="button ">Delete</a></p>
        </div>
    </div>
    <div id="divTemplate" style="display:none ">
        <p>Test <a href="# " class="del_button " role="button ">Delete</a></p>
    </div>
</body>
</html>

CSS:

#elementHolder div {
    border: 1px solid black;
    display:inline-block;
    padding: 0.5em;
    margin: 0.2em;
}

JS:

var counter = 100;
$(document).ready(function () {
    $("#elementHolder a.del_button").click(function (event) {
        event.preventDefault();
        var parentDiv = $(event.target).parent().parent();
        alert("Id: " + parentDiv.attr('id'));
    });
    $("#clickMe").click(function (event) {
        counter += 1;
        var newId = "webThumb" + counter;
        var newDiv = $("#divTemplate").clone(true, true);
        newDiv.attr("id", newId).prependTo("#elementHolder");
        newDiv.fadeIn(500);
    });
});

Any suggestions?

1
  • 1
    Why not use bubbling and not worry about cloning the events. $("#elementHolder").on("click", "a.del_button", function() {}); Commented Nov 20, 2013 at 18:04

2 Answers 2

1

It does not clone the event since there is no event to clone.

You never assign a click event to divTemplate, you only do it to elementHolder which divTemplate is not a child of.

Get rid of worrying about cloning the event and just use bubbling

$("#elementHolder").on("click", "a.del_button", function (event) {
    event.preventDefault();
    var parentDiv = $(this).closest("div");
    alert("Id: " + parentDiv.attr('id'));
});
Sign up to request clarification or add additional context in comments.

Comments

0

Use even delegation:

$("#elementHolder").on("click", "a.del_button", function() {
   //do stuff
});

http://jsfiddle.net/wD3dq/2/

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.