Reputation: 5
Is it possible to use JavaScript to get a variable into a tag because I want the progress bar to have the value of the variable, for example:
<progress max="100" value="Javascript Variable"></progress>
How would I be able to replace "Javascript Variable" with a variable?
Upvotes: 0
Views: 785
Reputation: 366
document.write()
is used to write directly in the <html>
element meaning you would overwrite everything in you document. You could use something like DOM's innerHTML
property to write directly in an HTML element (for example <div>
), but if that <div>
had some content/children they would be gone.
I think what you want to do is something like:
<div id="myProgress">
<div id="myBar"></div>
</div>
var i = 0;
function move() {
if (i == 0) {
i = 1;
var elem = document.getElementById("myBar");
var width = 1;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
i = 0;
} else {
width++;
elem.style.width = width + "%";
}
}
}
}
This is the example from https://www.w3schools.com/howto/howto_js_progressbar.asp
Basically, here we are altering the elements width
on click event. If you are fetching some data from the API you could use that time where we are waiting for the response to display some kind of loader/progress bar.
NOTE: you will never know how much time you will wait for an API's response, meaning it would have more sense to use a loader (circular loader for example - https://miro.medium.com/max/882/1*9EBHIOzhE1XfMYoKz1JcsQ.gif) instead of a regular progress bar (1% to 100%).
Hope this helps.
Upvotes: 0
Reputation: 173
When document.write() is executed after page load, it replaces the entire header and body tag with the given parameter value in string, it is uncommon task to overwrite an entire page, hence why using document.write() is bad practice.
Another reason not to use document.write() is it doesn’t support XHTML, but its not an issue since most web development uses HTML. Since document.write() fires after a page has finish loading, it causes performance issues and sometimes, may not even fire at all.
The only seem appropriate usage for document.write() is when working third parties like Google Analytics and such for including their scripts.
Here is the sample code to update the value of <progress>
function myFunction() {
document.getElementById("myProgress").value = "80";
}
<progress id="myProgress" value="8" max="100">
</progress>
<button onclick="myFunction()">Update</button>
Let me know if it helps you
Upvotes: 0
Reputation: 2655
This example might help you:
const myProgressBar = document.getElementById("progressBar");
const progressBarValue = 75; //custom value
myProgressBar.value = progressBarValue; //setting the value
<progress min="0" id="progressBar" max="100" value=""></progress>
Upvotes: 2