Joshua Ukaka
Joshua Ukaka

Reputation: 9

Incrementing a progress bar value with a function in JavaScript

I am trying to create a download button, which when clicked, displays a progress bar whose value is initially set to 0. And increases the value every 3s.

This is my code.

function download () {
    let x = 0
    let increase = setInterval(() => { 
        document.getElementsByTagName('progress').value = x + 10;
    }, 3000)
}

Upvotes: 0

Views: 142

Answers (1)

Michael M.
Michael M.

Reputation: 11070

First, you should add max attribute to your <progress> tag. Second, the issue with your code is that document.getElementsByTagName() returns a collection of elements, but you only want to get the first one:

function download () {
    let x = 0;
    const el = document.getElementsByTagName('progress')[0];

    // `max` does access a number value whereas
    // `getAttribute` accesses a string value.
    const { max } = el;

    let increase = setInterval(() => { 
        el.value = x += 10;
        if (x >= max) {
          clearInterval(increase);
        }
    }, 100);
}

download();
<progress value="0" max="100"></progress>

Also, as Peter Seliger noted, you only need to query the element once outside of the interval. You can also clear the interval once the value has exceeded the max.

Upvotes: 2

Related Questions