JQuery: wait for element (video tag - dynamically generated) to load

Without using a timeout, I want to use jQuery to validate a video tag that will be generated soon. At the time we look for a video tag, it doesn't exist yet.

I could use window.load to wait for the entire window to load, then call the callback function:

window.load = function () {player = jQuery("#videoid"; }

      

but still "wait" until this video tag is inserted / loaded into the body and then execute the callback function? something like:

jQuery("#videoid").bind('load', function() { player = jQuery("#videoid"); })

      

early

+3


source to share


1 answer


You can delegate event binding for an DOMNodeInserted

element, so when you insert an event handler, the event will be executed. This doesn't work in IE8 and older, but no tags <video>

:

jQuery(document).delegate('video', 'DOMNodeInserted', function () {
    alert('Wana watch a video?');
});

      

Please note that is the $(<root element>).on(<event>, <selector>, <event handler>)

same as $(<root element>).delegate(<selector>, <event>, <event handler>)

.

Here's a demo: http://jsfiddle.net/vW4Pg/



UPDATE

If you're interested in implementing this idea, don't forget to take a look at this: https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events

Thanks for @JFK's comment.

+9


source







All Articles