12

I want to append some HTML inside this div, and the HTML has to have a click event on it also.

    <div id="myID">
        <p>hello, world!</p>
    </div>

I want to insert a new div inside of the above div, and I want a click event on the new HTML I insert there. There will be some dynamic text inside the new div so it has to by dynamically created.

How can it be done?

4 Answers 4

15

What about :

$("#myID").click(
  function () {
     var someText = "my dynamic text";
     var newDiv = $("<div>").append(someText).click(function () { alert("click!"); });
     $(this).append(newDiv);
  }
)
Sign up to request clarification or add additional context in comments.

Comments

10

As of jQuery 1.3, this will work:

<div class="myClass">
<p>hello, world!</p>
</div>


$(".myClass").live("click", function(){
    $(this).after("<div class='myClass'><p>Another paragraph!</p></div>");
});

See more about live events on this page:

http://docs.jquery.com/Events

1 Comment

You were right, live method is the correct answer for this issue.
2

IMPORTANT:

Take into account that the performance should be better if you use the most specific selector. For this case, if you want only affect the divs inside the "MyId" div, you should use:

$("#MyId").on("click", "div", function(e) {
    // Whatever you want to do when the divs inside #MyId div are clicked
});

VERY IMPORTANT:

Take into account that the second parameter for the on method, in this case "div", is optional, but you NEED to provide it if you want the event to be automatically attached to the dinamically created items. This is called deferred in the jquery documentation for "on" method. I hope this info saves time for someone reading this in the future :)

Comments

0

Andrew solve this problem to me! But .live is deprecated in the recent versions of jquery (as of 1.7). Use .on or .delegate on top.document to bind these events types. See:

$(document).on(".myClass", "click", function(){
    $(this).after("<div class='myClass'>Another paragraph!</div>");
});

Congrats my friend!

1 Comment

wouldn't it be the other way around, "click",".myClass"?

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.