Javascript preloader / progress / percentage

I am having trouble finding good information on how to create a javascript (or jquery) progress bar with text that tells you a percentage.

I donโ€™t need a plugin, 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 preloaded images. Also, how do you change html / css and / or call a function based on the number of images loaded?

+8
javascript jquery progress-bar preloader
source share
2 answers
Items

<img> have an onload that fires after the image is fully loaded. Therefore, in js, you can track the number of images uploaded and the number of remaining with this event.

Images also have the corresponding onerror and onabort , which are triggered when the image does not load or the download was interrupted (the user clicked the "x" button). You also need to track them along with the onload in order to properly track the loading of images.


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 above example does not handle onerror or onabort for clarity, but real-world code should also take care of them.

+7
source share

How about using something below:

 $('#btnUpload').click(function() { var bar = document.getElementById('progBar'), fallback = document.getElementById('downloadProgress'), loaded = 0; var load = function() { loaded += 1; bar.value = loaded; /* The below will be visible if the progress tag is not supported */ $(fallback).empty().append("HTML5 progress tag not supported: "); $('#progUpdate').empty().append(loaded + "% loaded"); if (loaded == 100) { clearInterval(beginLoad); $('#progUpdate').empty().append("Upload Complete"); console.log('Load was performed.'); } }; var beginLoad = setInterval(function() { load(); }, 50); }); 

JSFIDDLE

You can also try the HTML5 progress element:

 <section> <p>Progress: <progress id="p" max=100><span>0</span>%</progress></p> <script> var progressBar = document.getElementById('p'); function updateProgress(newValue) { progressBar.value = newValue; progressBar.getElementsByTagName('span')[0].textContent = newValue; } </script> </section> 

http://www.html5tutorial.info/html5-progress.php

+3
source share

All Articles