Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Targeting elements added via *non-jQuery* AJAX before any Javascript events fire? Beyond the scope of live()?

Working on a Wicket application that adds markup to the DOM after onLoad via Wicket's built-in AJAX for an auto-complete widget. We have an IE6 glitch that means I need to reposition the markup coming in, and I am trying to avoid tampering with the Wicket javascript... blah blah blah... here's what I'm trying to do:

  1. New markup arrives in the DOM (I don't have access to a callback)
  2. Somehow I know this, so I fire my code.

I tried this, hoping the new tags would trigger onLoad events:

 $("selectorForNewMarkup").live("onLoad", function(){ //using jQuery 1.4.1
    //my code
});

...but have become educated that onLoad only fires on the initial page load. Is there another event fired when elements are added to the DOM? Or another way to sense changes to the DOM?

Everything I've bumped into on similar issues with new markup additions, they have access to the callback function on .load() or similar, or they have a real javascript event to work with and live() works perfectly.

Is this a pipe dream?

like image 632
peteorpeter Avatar asked Dec 31 '25 04:12

peteorpeter


1 Answers

.live() doesn't work like this, it's a common misconception. .live() creates an event handler at the DOM root and waits for events to bubble up to it. If the selector matches the event target, .live() will fire the bound event.

It doesn't look for new objects and bind events to them in any way, rather it just listens for a bubble, and doesn't care when that object was added to the DOM.

You need to fire whatever code is needed to run manually when your load operation completes.

What will this is the livequery plug-in, look specifically at the livequery( matchedFn ) call.

You can do something like this:

$('#myID').livequery(function() { $(this).offset()...stuff });
like image 144
Nick Craver Avatar answered Jan 02 '26 20:01

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!