Ben Stafford
Ben Stafford

Reputation: 155

How can I control a progress element using JavaScript for Loading visualization?

I need help with adding a loader to my HTML document. Here's the page without the loader:

<!DOCTYPE html>
<html>
  <head>
    <title>Webpage</title>
  </head>
  <body bgcolor="#FFFFFF">
    <script>
      /*
      
      Script goes here for the loader.
      I think I might have an idea, I could use the "load" event.
      
      */
    </script>
    <style>
      
      h1 {
        color: green;
        font: 24px Courier;
      }
      
      .css-format-class {
        color: red;
        font: 16px Arial;
      }
      
    </style>
    <center>
      <h1>My Simple Webpage</h1>
    </center>
    <br>
    <p class="css-format-class">I wish I could add a loader GIF onto this page...</p>
    <!--I need a loader somewhere in this webpage...-->
    <!--If you know the solution, please feel free to comment.-->
  </body>
</html>

I found this bit of code in HTML5, but don't know how to make JavaScript manipulate this tag:

<progress id="loader" value="0" max="100"></progress>

If you know how, let me know.

Upvotes: 1

Views: 963

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

Get a reference to the progress element (e.g. using document.getElementById()) and then update the value property, which maps to the attribute of the same name. See the snippet below for a demonstration, where setInterval() is used to call a function every second to update the value.

The code below waits until the DOM is ready by adding an event listener (using document.addEventListener()) to add a callback when the event DOMContentLoaded happens. That way it doesn't try to access elements in the DOM (e.g. the progress element) before it is ready.

var progress, date, interval;
// wait until DOM has been loaded to perform DOM Manipulations
document.addEventListener('DOMContentLoaded', function() {
  date = Date.now(); //current timestamp since UNIX epoch

  //get a reference to the progress element using its id attribute
  progress = document.getElementById('loader');
  interval = setInterval(updateProgress, 1000);
});
function updateProgress() {
    msg.innerHTML = 'begin updateProgress() - progress.value = '+progress.value + "<br>" + msg.innerHTML;
    if (progress.value >= 100) {
      //stop running this function after value reaches 100 (percent)
      clearInterval(interval);
    }
    var newDate = Date.now();
    var milliseconds = newDate - date;

    var seconds = Math.floor(milliseconds / 1000);
    loader.value += seconds;
  }
<progress id="loader" value="15" max="100"></progress>
<div id="msg" style="max-height:100px;overflow-y: auto"></div>

Upvotes: 1

Related Questions