I want to run some code when an image is loaded. Also, I'd like to do it unobtrusively (not inline). More specifically, I want to use jQuery's live()
function so it will happen for any dynamically loaded images.
I've tried:
<img class="content_image" alt="" src="..." />
<script>
$('.content_image').live('load', function() {
alert('loaded!');
});
</script>
In addition to load
, I've tried onload
, and onLoad
. When I replace with 'click' all works as expected so I know it's not some interfering bug.
I haven't been able to find a list of available event types for the live()
function, so for all I know, it may not be possible.
jQuery | live() Method This method is used to attach one or more event handlers for the selected elements. It also specifies the function that runs when the event occurs. The event handlers used will work for both current and future elements matching the selector.
$(document). ready(function(){ if (jQuery) { // jQuery is loaded alert("Yeah!"); } else { // jQuery is not loaded alert("Doesn't Work"); } });
on( "load", handler ) . The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
The onload property of an Image object specifies an event handler function that is invoked when an image loads successfully. The initial value of this property is a function that contains the JavaScript statements specified by the onload attribute of the <img> tag that defined the Image object.
(It would be load
, not onload
or onLoad
.)
load
doesn't bubble (according to the img
entry in the HTML5 spec, it's a "simple event", which don't bubble), so you can't use it with live
or delegate
, which rely on the event bubbling from an element to its ancestor element(s).
You'll have to hook it on the individual img
elements (and do so before you set their src
, since otherwise you can miss it; and always remember to watch for error
as well). (Yes, you really can miss it: The browser is not single-threaded, just the JavaScript main thread. If you set src
and the image is in cache or becomes available soon enough, the browser can fire the event. The way events are fired is that the browser looks to see what handlers are registered as of when the event is fired, and queues those to be called when the JavaScript main thread yields back to the browser. If there are no handlers registered, they aren't queued, and you never get the callback.)
it's a little bit dirty, but it works :
<script type="text/javascript">
var loop = setInterval(function() {
// the img to watch
var $img = $("img.hi");
if( !!$img.length && $img[0].complete ) {
// clear the timer
clearInterval(loop);
alert("loaded !");
}
}, 30);
</script>
<img class="hi" src="http://www.google.fr/images/nav_logo72.png" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With