Increasing a Div with Javascript to make it work as a progress bar

I am using a div tag to create a custom progress bar instead of using HTML5. I wrote some code that doesn't work perfectly. Here in the code I am trying to get the width of the inner div using javascript and parse it into an integer to get the numeric width to trigger the first IF condition, but I get the width of the inner div null, so the first IF condition will never get executed. The second IF condition is just an execution check, then clearing the div width to 0px and closing the spacing function.

<style type="text/css">
    #outer{
        width:300px; 
        height:50px; 
        background:#000; 
        border:1px solid #000;
    }
    #inner{
        background-color: rgba(255,255,255,0.5);
        margin:2px;
        width:0px; 
        height:46px;
    }
</style>
<script type="text/javascript">
    var increaseWidth = 0;
    function getID(element){
        return document.getElementById(element);
    }
    function progressBarEvent(){
        var interval = setInterval(function(){
                if(parseInt(getID('inner').style.width) < 296) {
                    getID('inner').style.width = increaseWidth+"px";
                    increaseWidth++;
                }
                if(getID('inner').style.width) == "296px"){
                getID('inner').style.width == "0px";
                increaseWidth = 0;
                clearInterval(interval);
                }
            }
            ,5
        );
    }
</script>
<div id="outer">
    <div id="inner">
    </div>
</div>
<button onclick="progressBarEvent()">Upload</button>

      

+3


source to share


1 answer


The problem is that the first time there is no style width

is the expression

parseInt(getID('inner').style.width)

      

will return NaN

. This way you never increase the width. You can fix it like this:

if ((parseInt(getID('inner').style.width) || 0) < 296) {
    getID('inner').style.width = increaseWidth + "px";
    increaseWidth++;
}

      



Also check your code, it currently contains a syntax error on this line:

if(getID('inner').style.width) == "296px"){
//   extra ) ----------------^

      

And one more problem: change getID('inner').style.width == "0px";

to getID('inner').style.width = "0px";

because you mean assignment here, not comparison.

Demo: http://jsfiddle.net/hrtkwbx9/1/

+2


source







All Articles