Saturday, July 11, 2009

JQuery selectors and future elements

I am using JQuery for the AJAX and dynamic aspects of my web based learning platform.

I like the fact that JQuery allows us to use CSS type selectors to select elements on the page to either manipulate them, add event handlers, or a host of other things.

So, the code below intercepts clicks on all links and dynamically adds a new link when a link is clicked.


<html>
<head>
<link rel="stylesheet" type="text/css" href="/site-media/al/style.css" />
<script type="text/javascript" src="./jquery-1.3.2.min.js"></script>
</head>

<body>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
$("ul#questions").append("<li><a href='#'>click me</a></li>");
});
});
</script>
<div>
<ul id="questions">
<li><a href="#">Click Me: 0</a></li>
</ul>
</div>
<textarea style="Width: 400px; Height: 200px" name="textarea" cols=20>
<head>


There is a problem with this code. Everytime you click on the link called "Click Me: 0" a new link is added, but if you click on the new link, then nothing happens. So, why does JQuery not work with dynamically added elements?

The reason is because the following call


$("a").click(function() {
//...
});


only binds to the anchor elements present on the webpage when the $(document).ready() function is called. It will not bind to future elements. To bind to future elements as well, we have to use the live() function.

Try using this code to bind to the "a" elements and it will work.

$("a").live("click", function() {
$("div#questions").append("click me");
});

1 comment:

நற்கீரன் said...

Thanks. This was useful.