Nik Sumeiko
Nik Sumeiko

Reputation: 8723

jQuery calls after HTML DOM selectors has been updated

When the document is ready, I am preparing click functions to some of the elements in such a way:

var divs = $("div a");
divs.click(function(){
  alert("clicked");

  return false;
});


var spans = $("span a");
spans.click(function(){
  $("div").append("<a>Another link</a>");
  alert("done");

  return false;
});

As you can notice, when user clicks on a link inside a <span>, I am appending new anchor into <div> element with append() function.

And than, when I click on those, just appended new anchors inside <div>, I am not getting alert("clicked"), which has to be?! But when clicking on default anchors, which hasn't been appended, alert still works for them?!


Than I am changing the code wrapping first part into a function:

function activateClick(){
  var divs = $("div a");
  divs.click(function(){
    alert("clicked");

    return false;
  });
}

// calling a function when page has been loaded
// to allow clicking on default anchors
activateClick();

var spans = $("span a");
spans.click(function(){
  $("div").append("<a>Another link</a>");

  // calling a function when new anchors appended
  activateClick();
  alert("done");

  return false;
});

And at the end, new anchors, which has been appended into <div>, are giving an alert("clicked"), but those default ones, gives this alert() more than one time, depends on how many times I have been called a function?!

Why so?! I need that always one alert appear!

Upvotes: 0

Views: 219

Answers (2)

user530954
user530954

Reputation: 1

var spans = $("span a");

spans.click(function(){
  var __a = $("<a>Another link</a>").appendTo("div");
  __a.click(function() {
      alert("clicked");
      return false;
  });
  alert("done");
  return false;
});

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630389

Use .live() here so it works on anchors created later:

$("div a").live("click", function(){
  alert("clicked");    
  return false;
});

$("span a").click(function(){
  $("div").append("<a>Another link</a>");
  alert("done");
  return false;
});

If you always have that one <div>, then use .delegate() instead, which is a bit cheaper, like this:

$("div").delegate("a", "click", function(){
  alert("clicked");    
  return false;
});

Upvotes: 3

Related Questions