Nick
Nick

Reputation: 25

HTML5 Progress Element Scripting

I'm trying to display a HTML5 progress element to show the download progress of a large image file.

I've checked a few answers to similar questions already posted on this forum but they don't seem to directly answer the question (or more likely it's just my ignorance) or they get very technical and therefore way beyond me.

I've downloaded a HTML5 / JavaScript example file that shows the basic method (see code below) but I can't figure out how to link this script to my image download.

Any advice would be greatly appreciated.

<!DOCTYPE html>
<html>
<head>
<title>Developer Drive | Displaying the Progress of Tasks with HTML5 | Demo</title>
<script type="text/javascript">

var currProgress = 0;

var done = false;

var total = 100;

function startProgress() {

var prBar = document.getElementById("prog");

var startButt = document.getElementById("startBtn");

var val = document.getElementById("numValue");

startButt.disabled=true;

prBar.value = currProgress;

val.innerHTML = Math.round((currProgress/total)*100)+"%";

currProgress++;

if(currProgress>100) done=true;

if(!done)
setTimeout("startProgress()", 100);

else    
{
document.getElementById("startBtn").disabled = false;
done = false;
currProgress = 0;
}
}
</script>
</head>
<body>

<p>Task progress:</p>
<progress id="prog" value="0" max="100"></progress> 
<input id="startBtn" type="button" value="start" onclick="startProgress()"/>
<div id="numValue">0%</div>

</body>
</html>

Upvotes: 1

Views: 698

Answers (1)

1ace
1ace

Reputation: 5288

If you are looking to track the progress of an XMLHttpRequest (which could be loading an image, or anything else), Adobe has a great example there. Ctrl+U is your friend :)

Basically, you'll want to do that:

var xhr = new XMLHttpRequest();
xhr.onprogress = function(e){

  // This tests whether the server gave you the total number of bytes that were
  // about to be sent; some servers don't (this is config-dependend), and
  // without that information you can't know how far along you are
  if (e.lengthComputable)
  {

    // e.loaded contains how much was loaded, while e.total contains
    // the total size of the file, so you'll want to get the quotient:
    progressBar.value = e.loaded / e.total * 100;

  }
  else
  {
    // You can't know the progress in term of percents, but you could still
    // do something with `e.loaded`
  }
};

Mozilla's Developer site has some more details, if you want to see what can be done.

Hope that's enough for you :)


PS: Now that I think about it, I see no reason not to use the e.total as progressBar.max, and simply push e.loaded into progressBar.value

Upvotes: 3

Related Questions