Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  186] [ 6]  / answers: 1 / hits: 17781  / 11 Years ago, tue, march 12, 2013, 12:00:00

I'm having trouble finding any good information on how to make a javascript(or jquery) progress bar WITH text that tells you the percentage.



I don't want a plug in, I just want to know how it works so that I can adapt it to what I need. How do you preload images and get a variable for the number of images that are preloaded. Also, how do you change html/css and-or call a function, based on the number of images that are loaded already?


More From » jquery

 Answers
3

<img> elements have an onload event that fires once the image has fully loaded. Therefore, in js you can keep track of the number of images that have loaded vs the number remaining using this event.



Images also have corresponding onerror and onabort events that fire when the image fails to load or the download have been aborted (by the user pressing the 'x' button). You also need to keep track of them along with the onload event to keep track of image loading properly.






Additional answer:



A simple example in pure js:



var img_to_load = [ '/img/1.jpg', '/img/2.jpg' ];
var loaded_images = 0;

for (var i=0; i<img_to_load.length; i++) {
var img = document.createElement('img');
img.src = img_to_load[i];
img.style.display = 'hidden'; // don't display preloaded images
img.onload = function () {
loaded_images ++;
if (loaded_images == img_to_load.length) {
alert('done loading images');
}
else {
alert((100*loaded_images/img_to_load.length) + '% loaded');
}
}
document.body.appendChild(img);
}


The example above doesn't handle onerror or onabort for clarity but real world code should take care of them as well.


[#79654] Monday, March 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
willieelisham

Total Points: 201
Total Questions: 108
Total Answers: 106

Location: Zambia
Member since Sat, Oct 31, 2020
4 Years ago
willieelisham questions
Wed, Apr 14, 21, 00:00, 3 Years ago
Wed, Mar 31, 21, 00:00, 3 Years ago
Sun, Oct 11, 20, 00:00, 4 Years ago
Sat, May 9, 20, 00:00, 4 Years ago
;