views:

267

answers:

4

I have a hyperlink with an ID when clicked will perform a certain event using JQuery. JQuery records the existence of this link on document load. Some time during the course of the users visit. I remove that link and the re-add it later. However, that even is not fired off again when that link is clicked after it has been removed and added.

Why is the case and how can I remedy it? Something to do with event binding?? Or shall I just add an onclick attribute?

+1  A: 

Don't remove the link from the DOM tree. Instead just toggle its visibility with show() and hide().

Removing the element from the DOM tree with remove() will remove the element and all of it's event handlers, even if you add it back eith the same id.

Triptych
+1  A: 

You will need to bind that event handler to the new element when it is added or you could use live() instead of bind to achieve what you need.

Basically, the event handler references the original element. When that element is removed, even though a new element is added with the same id, it is a different element.

Russ Cam
A: 

If you completely remove the element, you will need to reattach any event listeners to the element when you recreate it.

Alternatively, just hide the element by setting its style to display:none with .show() and .hide()

Paul Dixon
+3  A: 

You've been using a tag like this to add the click event:

$('#speciallink').click(function(){
  // do something
  return false;
});

This will bind the event to the elements that are selected at that moment.

Removing a link and adding it again, will effectively create a new element, without this event. You can use the "live" method to add rules that will be applied to events matching the rule, even when these elements are created after creating the rule:

$('#speciallink').live("click",function(){
  // do something
  return false;
});
Scharrels
+1 for being the first person to mention live events
Neil Aitken
Thanks! I just keep on learning. :)
Abs