Javascript/jQuery HasLoaded or equivalent? - javascript

I know in jquery it is possible to call the javascript/jquery onload()/load() functions on, for example an image (<img>).
However, if in jquery if i use .html(htmlString) to insert an image after the dom has loaded, how can i add a listener to handle the images onload event? Is there a property I can check to see various images and if they have loaded?

After appending your html, you can bind the load event to the contained images:
$("#foo").html(htmlString).find("img").one("load", function() {
...
}).each(function() {
// image has been cached, so load event won't fire unless we explicitly call it
if(this.complete) $(this).trigger("load");
});

Check the complete property of the image(s)

Related

Can´t attach eventlistener to onload event of <img>-Tag

I am wondering why I can´t attach an eventlistener to the onload event of an html image.
<img id="imageID" onload="doSomething();"> works perfectly,
but if I want to add a listener like
document.getElementById('imageID').addEventListener('onload', function(e) {
doSomething();
});
or with jQuery
$("imageID").on("onload", function(){
doSomething();
});
the event is not being catched. If I listen for a simple "click"-Event it works, but not with the "onload"-Event.
Can anybody tell my the reason for this behaviour?
Don't include "on" in the event name.
// no "on"------------v
document.getElementById('imageID').addEventListener('load', function(e) {
// no "on"----v
$("#imageID").on("load", function(){
// ^----need "#"
There are two problems here.
You don't put "on" in the event name, as I Hate Lazy said.
If you're trying to hook the load event on an image that's already on the page, you'll have a race condition and sometimes won't see the event, because it can be "loaded" the instant that it is put on the page (if the relevant image is in cache). You have to hook load before the image has a src attribute, which typically means adding the image dynamically. Your DOM0 handler (the onload="doSomething()") works because it's already attached when the image is added to the document, but anything looking the image up on the page later (getElementById or jQuery) may miss it.

jQuery Event Listeners

Is there a way using jQuery to add event listeners much like the ones that are available in AS 3.0?
For example, if you load an image, (setting it's opacity to zero so that it doesn't appear on screen) does jQuery have something similar to an onComplete event listener that listens out for when load has completed? Once the load has successfully loaded then you could fire off another function to fade it's opacity back to 1 again.
I've seen a few plugins that have been written, but thought I'd ask a question to see if anyone has found an solution without the use of 3rd party plugins.
Thanks.
Something like this?
$(function(){
$("img").hide().load(function(){
$(this).fadeIn();
});
});
The first line is shorthand for $(document).ready(function(){
Then we simply select all the img elements, and hide them and add a load handler to them which fades them in.
Although, if cached the above could prove to be trouble. The below would solve this.
$(function(){
$("img").hide().each(function(){
if(!$(this).width()){ // image dimensions are unavailable if it's not loaded
$(this).load(function(){
$(this).fadeIn();
});
}else{ //if the image is loaded already
$(this).fadeIn();
}
});
});

jQuery .html function with .load

I am loading HTML content using jQuery's .html() function. Part of the HTML content I am trying to load are images, which take some time to be loaded. What I do is on an onclick event,
$('div').on('click',function() {
$('html').fadeOut(1000)
.html(content)
.load(function() {
$('html').fadeIn(1000)
});
});
What I wanted to happen is that, when the DOM has finished loading, I want it to fadeIn. If it is still not finished, I want it to stay hidden hence, the fadeOut function before the html load.
Is this possible? That method doesn't seem to work for me.
First, if you are replacing the entire HTML element, you might as well just do a full request cycle. That's essentially what you're going to end up with and it will be easier to hook to the window load event using a full request than to handle this with AJAX. If you're not replacing the entire page, then you've got your selector wrong.
Second, if you are just loading the DIV, then you can try hiding the DIV, binding the load event to it, then loading it with content. See the caveats for the http://api.jquery.com/load-event/ method for more information.
$('div').on('click',function() {
var $this = $(this); // save reference for future use
$this.fadeOut(1000) // hide
.load(function() { // hook up handler
$this.fadeIn(1000)
})
.html(content); // load content
});

how to handle onLoad Event on img tag and others

how to handle onLoad Event on img tag?
example:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src'));
})
is like the imageLoader
and others tags like script, link, etc...
jQuery callback on image load (even when the image is cached)
$("img").one('load', function() {
// do stuff
}).each(function() {
if(this.complete) $(this).load();
});
Seems to work for me, and should fix the caveat with caching.
There's an example of how to do this right on the jQuery doc page for .load().
HTML:
<img src="book.png" alt="Book" id="book" />
Javascript:
$('#book').load(function() {
// Handler for .load() called.
});
And, there are a bunch of caveats to watch out for listed on that jQuery page too.
With images, if you want to assure that the load handler gets called, the load handler has to be set before the image can possibly be loaded. If you're constructing the image in code, that means you have to set the load handler before you set the .src attribute. That's because, in some browsers, if the image is in the memory/disk cache, it will load immediately when you assign .src and if you then subsequently set the .load() handler, you will be too late (the image will already be loaded) and the .load() handler will never be called.
I don't know how to guarantee that a jQuery-based .load() always gets called for an image that's in your page HTML because you can't assign the event handler until the object exists, but once the object it exits, it might already be loaded. You can use non-jQuery setting of an onload=xxx in the actual HTML though that is an older style of coding. Of course, you can always hook window.onload to know when all page images (and other resources) have been loaded.
jQuery has a load method, not onload. And your code should probably be:
$ ('img').load(function () {
alert('image loaded ' + this.src);
})

assign event to div when it has loaded fully

Can I assign an event to a div to fire when all elements of the containing div have loaded fully? eg. if the div contains an image, fire an event on the div when the image has loaded fully. I am using jquery.
Not sure how you're dynamically adding your content, but this example should illustrate how it could work.
It is using .append() to simulate your dynamically loaded content. Then after the append, it uses .find() to find the images, and .load() to attach a load handler to them.
Finally, it returns the length property of the images. Then in the load handler, as the images finish loading, the length is decremented. Once it gets to 0, all the images are loaded, and the code inside the if() runs.
Example: http://jsfiddle.net/ehwyF/
var len = $('#mydiv').append('<img src = "http://dummyimage.com/150x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/160x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/170x90/f00/fff.png&text=my+image" /><img src = "http://dummyimage.com/180x90/f00/fff.png&text=my+image" />')
.find('img')
.load(function() {
if( --len === 0) {
alert('all are loaded');
}
}).length;
This way, the code runs based only on the images in #mydiv.
If there are any images in there that were not dynamic, and therefore shouldn't get the .load() event, you should be able to add a .not() filter to exclude ones the complete property is true.
Place this after the .find() and before the .load().
.not(function(){return this.complete})
If it's just one image you're wanting to wait for you can load the image with ajax and then trigger the event in the ajax callback.
It's hard to check it for just one div, but may I suggest using $(window).load() to check if all the images have loaded?
UPDATE:
If you using ajax then use the callback to see when the json has loaded, and then attach $("div#id img").load() to see when all the images have loaded. Only problem with this is that I have noticed when the image is cached, the loader does not get triggered. :(
To add to Shadow Wizard's idea, you could try the following code:
var totalImages = $(".yourImageClass").length;
var loadedImages = 0;
$(".yourImageClass").bind("onload", function() {
loadedImages++;
if (loadedImages == totalImages) {
//all images have loaded - bind event to DIV now
$("#yourDiv").bind(eventType, function() {
//code to attach
});
}
});
Catch the onload event of all images in the div, in there raise some global counter by 1. If that counter is equal to the amount of images in the div... all images finished loading.
Should be simple using jQuery.
This will work only for images though, other elements don't have onload event.

Categories