Home > Net >  How to make score progress bar HTML/CSS/JS
How to make score progress bar HTML/CSS/JS

Time:12-29

I am trying to do a 5 segment progress bar for score keeping app. 2 Players, each will have their own progress bar (5 divs in grid next to each other). I have 2 buttons (P1 and P2) whenever one of those is pressed, point is added to appropriate player. I want to have a visual representation that will fill in one of 5 divs with a color upon adding a point. I do have a logic for changing score, and stopping game once one of the players hit 5 points. I don't want to use element, and I want for each progress bar to start filling segments from outer to inner (so player 2 will have reversed order) But I have no clue how to go about changing background color of a single segment for button presses. Should all scoreBox divs have unique IDs?

My score keeping mockup

HTML


    <div >
        <div >
            <h1><span id="p1score">0</span> to <span id="p2score">0</span></h1>
        </div>
        <div >
            <div >
                <div ></div>
                <div ></div>
                <div ></div>
                <div ></div>
                <div ></div>
            </div>
            <div >
                <div ></div>
                <div ></div>
                <div ></div>
                <div ></div>
                <div ></div>
            </div>
        </div>

I tried finding a way to select each box for button press, but wasn't successful.

CodePudding user response:

To select a particular score box, you can use the :nth-child pseudo class.

For example, .p1gfx > :nth-child(1) gets the first score box of the first player, .p1gfx > :nth-child(2) gets the second score box of the first player, and so on.

I would recommend adding a CSS class for the background color. For example:

.point {
    background-color: green;
}

To add or remove color from a box, you can then just add or remove the CSS class to the element. For example, to change the background color of the first box of the first player to green, you can do this:

const box = document.querySelector('.p1gfx > :nth-child(1)');
box.classList.add('point');

CodePudding user response:

Use unique id for each players: use unique id for player one segment and player two segment

  • Related