never_had_a_name
never_had_a_name

Reputation: 93146

use jquery on DOM that has been added afterwards with jquery?

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?

Upvotes: 0

Views: 101

Answers (3)

VolkerK
VolkerK

Reputation: 96159

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 function(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");
    });
  });
});

Upvotes: 1

Mark Ursino
Mark Ursino

Reputation: 31435

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

$("#new_link").live("click", function(){
  // your code here
}

Upvotes: 0

Funky Dude
Funky Dude

Reputation: 3957

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

$("#new_link").live('click',function(){});

Upvotes: 1

Related Questions