Search code examples
javascripthtmlcssprogress-barprogress

elem.style.height not triggered inside while loop


I want to make a progress bar that "collapses" when done.
By collapse, I mean repeatedly decrease height by 1.

But when the progress bar "is done" (reaches width 100), nothing more happens.

This is my code:

               function frame() {
                    var elem = document.getElementById("myBar");
                    var height = 30;
                    if (width >= 100) {
                        while (elem.style.height != 0) {
                            elem.style.height = height + '%';
                            height--;
                        }
                        clearInterval(id);
                    } else {
                        width++; 
                        elem.style.width = width + '%';
                    }
                }

Where is the error?

Sorry if my question is silly or a duplicate; I searched the forum but found no duplicate post.

Thanks in advance


Solution

  • As you have done this

     elem.style.height = height + '%';
    

    The following will never be false:

    while (elem.style.height != 0) 
    

    Becase this is false:

    "0%"==0 // false
    

    And I think there is something wrong with the loop. If you want to decrease the height one by one, it is better to call a setInterval, as a loop will change the height to 0 in less than 1ms, which has no difference with setting the height to 0 directly.