Search code examples
javascripthtmlcssprogress

progress bar movement calculation


Because I can change the winning score in the game, I'd like the progress bar to be sensitive to it. Now, it accepts percentages relative to the total height of a div. The default score is 100pts. And the progress bar is set to move from 0%(min) ~ 100%(max) which is 100pts - the winning score. Could you suggest me some ideas how to program the progress bar that when a user inputs the winning score of, for example, 50 pts which will be 100%(max), then when the player reaches 25pts, the progress bar will display that he's half way (50%) from winning the game. I hope my explanations are clear.

HTML input:

<input class="score-input" type="text">

function to set the winning score (100 by default)

function setWinningScore() {
        let inputScore = document.querySelector('.score-input').value;
            if (inputScore) { 
                winningScore = inputScore;
            } else {
                winningScore = 100; 
            }   
        }

Progress bar function which reads the player's score, the progress bar element's id and then reflects it.

function progressBar(myScore, progBarId) {
    progBarId.style.height = myScore + '%';
}

Solution

  • You almost answered your own question.

    Since you know that 25 out of 50 is 50%, then you should also know that 25/50 = 0.5

    With that you can simply multiply it by 100 and that gives you your percent.

    0.5 * 100 = 50

    As Johan Karlsson pointed out, you would just replace your progressBar function with the following:

    function progressBar(myScore, progBarId) {
        progBarId.style.height = ((myScore / winningScore) * 100) + '%';
    }
    

    I would add that you should also make your setWinningScore function a bit safer by making sure that the given input is a valid positive number, otherwise you'll have some problems.

    function setWinningScore() {
            let inputScore = document.querySelector('.score-input').value;
                if (typeof inputScore === 'number' && inputScore > 0) { 
                    winningScore = inputScore;
                } else {
                    winningScore = 100; 
                }   
            }