Question:
How to unhide progress bar when button is pressed and then update?

Consider using the> <progress> element were you just need to se the value.

To prevent starting the loop twice, consider checking the PID.


let id = null;


document.getElementById("submit-btn").addEventListener("click", function() {


    document.getElementById("progress-top").style.display = 'block';

       

    if (id === null) {

        var val = 1;

        id = setInterval(frame, 50);


        function frame() {

            if (val >= 100) {

                clearInterval(id);

                id = null;

            } else {

                val++;

                document.getElementById('progress').setAttribute('value', val);

            }

        }

    }

})


.progress {

    height: 150px;

}


<div class="progress" style="display: none" id="progress-top">

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

</div>


<button id='submit-btn'>Click me</button>


Regarding the Bootstap variant, you'll need to set both style.width and innerHTML.

The aria-valuenow doesn't need to be updated.

let id = null;


document.getElementById("submit-btn").addEventListener("click", function() {


    document.getElementById("progress-top").style.display = 'block';

       

    if (id === null) {

        var val = 1;

        id = setInterval(frame, 50);


        function frame() {

            if (val >= 100) {

                clearInterval(id);

                id = null;

            } else {

                val++;

                document.getElementsByClassName('progress-bar')[0].style.width = val + '%';

                document.getElementsByClassName('progress-bar')[0].innerHTML = val + '%';

            }

        }

    }

})


.progress {

    height: 150px;

    width: 200px;

}


<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet"/>


<div class="progress" id="progress-top" style="display: none">

  <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100"></div>

</div>


<button id='submit-btn'>Click me</button>



Suggested blogs:

>Javascript Error Solved: Property 'id' does not exist on type 'T'

>Why highlighted table row using class not working in JavaScript?

>How to rename an object key based on the condition in JavaScript?

>How to sort an array based on another array in Javascript?

>Javascript: Modal not closing with a button


Nisha Patel

Nisha Patel

Submit
0 Answers