tags:

views:

49

answers:

3

here is the case. with jquery ajax call i have added a new link < a id="new_link >

and i want to use jquery on that newly added link:

    $(document).ready(function(){

    $.post("static/js/jquery_call.php", function(data){
        $("#div_id").html(data);
    });

    $("#new_link").click(function(){

    ..... (and so on)

but it doesnt allow me because this link was added after the DOM has been generated. I can manipulate all other links but not the new added one. How can i solve this?

+1  A: 

this question is asked every other day. boy, have i milked from it

$("#new_link").live('click',function(){});
Funky Dude
+1  A: 

Your function(data) handler is invoked when the ajax request is finished (all data present). In the meanwhile the execution of the script continues. Meaning that your $("#new_link")... code most likely is executed before the data has been added to the dom.
Either use a live handler or at least move your $("#new_link") code inside the funtion(data) { } handler.

edit: example code

$(document).ready( function(){
  $.post("static/js/jquery_call.php", function(data){
    $("#div_id").html(data).find("#new_link").click( function() {
      alert("Test");
    });
  });
});
VolkerK
A: 

Use the .live() function (doc here) to bind to existing and newly created elements:

$("#new_link").live("click", function(){
  // your code here
}
Mark Ursino
can i ask you how you could answer this fast? do you subscribe to new threads? or did you just click on this tread but accident?
never_had_a_name
Haha, I was in the jQuery-tagged section and I happened to hit refresh and saw the new question and immediately knew the answer. I'm taking a break at work :-D
Mark Ursino
ok i c=) is it possible to subscribe to new messages in your favurite tags? i have not an account yet.
never_had_a_name
You can use the RSS feed (right corner of your address bar) or jsut look at specific tags, e.g. http://stackoverflow.com/questions/tagged/jquery -- content comes in so fast that you can wait 10 seconds, hit refresh and there is a lot of new stuff.
Mark Ursino