0

I have some code which adds a tooltip to all links. Now, the page keep changing with AJAX - how can I track these changes and add tooltips to links which are added to the document by AJAX?

I thought this might work:

$(document).live('change', function(){

    //code...

});

But I'm guessing there's a smarter/more efficient method to work this out. Any ideas?

Note: I can only use jQuery 1.3.2

Rohan
  • 3,645
  • 4
  • 22
  • 16

2 Answers2

2

You're close, but I think you might be misunderstanding the .live() function.

What .live() does is establish the monitoring for you - it looks at the DOM changes in the page and decides if new elements that match the selector have shown up. If they have, then it attaches the specified function to them.

Try something like this:

$("a").live('mouseover', function(){

    //code...

});

What this does is start monitoring the DOM for any <a> elements that get added to it, and when a new element is detected, it attaches the function to the mouseover event for that element.

womp
  • 115,835
  • 26
  • 236
  • 269
  • Thanks, makes it a bit clearer. The problem is, I don't actually manage the mouseover. My current code is: `$('a').each(function(){ //add tooltip plugin code });` So how would I manage the live here? – Rohan Jul 01 '10 at 04:58
  • Presumably the tooltip plugin code isn't accessible to you so that you can't duplicate what it's doing, so you might need to take a different approach, since .live() only works for event handlers and custom events. Maybe try this approach? http://forum.jquery.com/topic/how-to-get-notified-when-new-dom-elements-are-added – womp Jul 01 '10 at 05:07
  • that new approach might have a problem in IE, http://stackoverflow.com/questions/2143929/domnodeinserted-equivalent-in-ie – Reigel Gallarde Jul 01 '10 at 05:13
0

.live() is the best way to handle AJAX addition of elements and event binding.

Much easier than finding each link on an AJAX update and doing the bind again.

Alastair Pitts
  • 19,423
  • 9
  • 68
  • 97
  • Could you give me an example of how exactly I'd make it work in this instance? – Rohan Jul 01 '10 at 04:49
  • How are you adding the tooltips? On a mouse over? Can you should us the `AddTooltips` code? – Alastair Pitts Jul 01 '10 at 05:04
  • `$('a').each(function(){ $(this).tooltip(); })` I'm using the plugin here: http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/ – Rohan Jul 01 '10 at 05:09