jriff
jriff

Reputation: 1977

Bind to anchor in jQuery

I have a page where I do:

$(document).ready(function(){
   $("a.notifypop").bind('click', function(){
       // Do stuff
       return false
   });
});

When I replace the content of the page I also replace the anchor that I have bound the click event to. The result is that the click event is no longer bound to the anchor - what to do in that situation? I HAVE to replace the anchor.

Upvotes: 0

Views: 2822

Answers (3)

Raynos
Raynos

Reputation: 169401

You can use .delegate instead. .delegate is significantly cheaper then .live And will bind to all all elements matching the selector.

See the documentation on .delegate

$("body").delegate("a.class", "click", function() {
    // do stuff
});

See Nick Craver's Answer as to why .delegate is better

Upvotes: 2

sethvargo
sethvargo

Reputation: 26997

You need to bind with .live, not .bind. .bind only applies to objects that exist at DOM load. Anything you create via JS, jQuery, AJAX, etc. that didn't exist at page load must be bound with .live for functionality.

$("a.notifypop").live('click', function(){
  // Do stuff
  return false;
});

Upvotes: 1

Jason Benson
Jason Benson

Reputation: 3399

If your new anchor has the same class:

$('a.notifypop').live('click', function(){
});

Upvotes: 0

Related Questions