In this very simplified and minimized example click event handler has been defined for every a tag (simple alert is displayed after link is clicked). Once you click the button, second link is added to the page.
But if you click this newly added link, event handler wan’t be called. Any idea why? What should be added/changed so that newly added elements are aware of the scripts defined on the main page?
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$("a").click(function() {
alert("link is clicked");
return false;
});
$("#btn").click(function() {
$("#second").html("<a href='#'>Second link</a>");
});
});
</script>
</head>
<body>
<div id="first">
<input id="btn" type="button" value="Get new content"/>
<a href="#">Original link</a>
</div>
<div id="second"/>
</body>
</html>
In this particular case, what should be done so that second link is aware of event handler defined in script section so that alert is being displayed after link is clicked?
What’s your advice on resolving these kind of situations? How do you make newly added elements on the page be aware of previously defined Javascript code?
Because you’re binding to all the existing links on the page. Try:
jQuery’s
livefunction actually attaches an event handler todocument.bodyand then checks to see if the event matches when it eventually bubbles up to body. So it will work for all current and future objects on the page.Note that if these links are in a particular container, this code is more efficient:
delegateonly checks events that bubble up to#container, so jQuery doesn’t check against every click anywhere on the page.