I know that for the image onload to work you have to set the src after the onload handler was attached. However I want to attach onload handlers to images that are static in my HTML. Right now I do that in the following way (using jQquery):
<img id='img1' src='picture.jpg'>
$('#img1').load( function() {
alert('foo');
})
.attr('src', $('img1').attr('src'));
But this is rather ugly and has the obvious flow that it can only be done for selectors that match only one image. Is there any other, nicer way to do this?
edit
What I meant by that it can only be done for selector that match only one image is that when doing this:
<img class='img1' src='picture.jpg'>
<img class='img1' src='picture2.jpg'>
$('.img1').load( function() {
alert('foo');
})
.attr('src', $('.img1').attr('src'));
That both images will have src='picture.jpg'
Description. 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.
Preload the image and replace the source of the <img /> after the image has finished loading. Show activity on this post. You can use the complete property to check if the image has finished loading.
Using the <img> tag. The <img> element is the most straight-forward way of displaying a static image on a page. You should normally use it whenever an image is actually a part of the content (as opposed to using an image as part of a page's design). All <img> tags must have a defined src attribute.
You can trigger the event (or it's handler) directly by calling .trigger()
or .load()
.
If you know that you want the event, because you know that the images are already loaded, then you can do it like this:
$('#img1').load(function() {
alert('foo');
})
.trigger('load'); // fires the load event on the image
If you are running your script on document ready or some moment where it isn't yet clear if the images are there or not, then I would use something like this:
$('img.static')
.load(function(){
alert('foo');
return false; // cancel event bubble
})
.each(function(){
// trigger events for images that have loaded,
// other images will trigger the event once they load
if ( this.complete && this.naturalWidth !== 0 ) {
$( this ).trigger('load');
}
});
Be warned that the load event bubbles (jQuery 1.3) and you might possibly be triggering a load handler on the document prematurely if you don't cancel the bubble in the img handler.
For the record: The img.src=img.src
triggering solution will unfortunately not work correctly on Safari. You will need to set the src
to something else (like # or about:blank) and then back for reload to happen.
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