Reputation: 9891
Without using timeout, I want to use jQuery to check for a video tag which is soon to be generated. At the time we are looking for the video tag, it does not exist yet.
I could use window.load to wait for the whole window loaded, then call the callback function:
window.load = function () {player = jQuery("#videoid"; }
but is there anyway to "wait" until that particular video tag inserted/loaded into the body then execute the callback func? something like:
jQuery("#videoid").bind('load', function() { player = jQuery("#videoid"); })
thanks in advance
Upvotes: 3
Views: 6029
Reputation: 75993
You can delegate a bind to the DOMNodeInserted
event for the element so when it's inserted an event handler will run. This doesn't work in IE8 and older, but neither do <video>
tags:
jQuery(document).delegate('video', 'DOMNodeInserted', function () {
alert('Wana watch a video?');
});
Note that $(<root element>).on(<event>, <selector>, <event handler>)
is the same as $(<root element>).delegate(<selector>, <event>, <event handler>)
.
Here is a demo: http://jsfiddle.net/vW4Pg/
UPDATE
If you're interested in implementing this idea, make sure to take a look at this: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
Thanks for the comment @JFK.
Upvotes: 10