This question already has an answer here:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("h2").html("<p class='test'>click me</p>")
});
$(".test").click(function(){
alert();
});
});
</script>
</head>
<body>
<h2></h2>
<button>generate new element</button>
</body>
</html>
I was trying to generate a new tag with class name test
in the <h2>
by clicking the button. I also defined a click event associated with test
. But the event doesn't work.
Can anyone help?
You CAN add on click to dynamically created elements. Example below. Using a When to make sure its done. In my example, i'm grabbing a div with the class expand, adding a "click to see more" span, then using that span to hide/show the original div.
Best way to apply event on dynamically generated content by using delegation.
so your code is like this now
Use 'on' as click gets bind to the elements already present.
For e.g
This will help.
.live function works great.
It is for Dynamically added elements to the stage.
Cheers, Ankit.
Reason:
In jQuery, Click()- attaches the event handler only if the element already exist in the html code.
It won't consider the new element which is created dynamically(Future element) after the page loaded.
Dynamic elements are created with the help of javascript or jquery(not in html).
So the click event doesn't fire.
Solution :
To overcome this we should use on() function.
delegate(),live() and on() functions have the advantages over the DOM elements.
on can trigger both existing elements as well as future elements.
on can consider the elements which are all present in the whole page.
delegate(),live() functions are deprecated(Don't use these).
You should use on function to trigger the event on dynamically created (future) elements.
Remove the code from $(document).ready:
Change into:
The
click()
binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by usingon()
.Source
Here's what you're looking for:
The above works for those using jQuery version 1.7+. If you're using an older version, refer to the previous answer below.
Previous Answer:
Try using
live()
:Worked for me. Tried it with jsFiddle.
Or there's a new-fangled way of doing it with
delegate()
:An updated jsFiddle.