calculation of progress bar advancement

I want to make the progress bar in my game responsive to changes in the winning score. Currently, it moves from 0% to 100%, which is equivalent to 100 points - the default winning score. But I need the progress bar to adjust accordingly based on the user-inputted winning score. For example, if the winning score is set to 50 points, reaching a score of 25 should display the player as halfway towards winning (50%). Can you help me figure out how to program this feature for the progress bar? I hope my explanation is clear.

HTML input:

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

Function to set the winning score (default is 100):

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

Progress bar function that updates based on player's score and the progress bar element's ID:

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

Answer №1

It seems like you're on the right track to answering your own question.

If you already understand that 25 out of 50 is 50%, then it should be easy for you to calculate 25/50 = 0.5

All you need to do next is multiply by 100 to find the percentage.

0.5 * 100 = 50

In line with Johan Karlsson's suggestion, you can update your progressBar function with this snippet:

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

I also recommend enhancing your setWinningScore function to ensure the input is a valid positive number for smoother operation.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the first character position be reached by moving the cursor using the jquery mask plugin?

I have done a lot of research but couldn't find the exact same question with a satisfactory answer. Therefore, I decided to ask a more specific question. I am using the Jquery mask plugin and I want my cursor to always be at the beginning of the textb ...

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...

Passport is raising a "missing credentials" error upon return

Hello everyone! I'm currently working on a password reset form and encountering an issue. When I submit the email in my POST form, I'm seeing a frustrating "Missing credentials" error message. This is preventing me from implementing the strategy ...

Guide on determining the total count based on a specific condition with the help of jQuery

Using AJAX, I have successfully retrieved all status values such as Active, ACTIVE_DRAFT, and Pending. However, I only want to select the statuses that are equal to ACTIVE. To do this, I am using an if condition which is working fine. After filtering by st ...

Using CSS to show only the central portion of an image

How can I display only the center part of an image with dimensions height=300px and width=520px using CSS or jQuery? I tried searching on Google, but didn't find a solution. Is it possible to show only a 200x130 section from the center of an image us ...

Modifying the hue of Material UI tab label

I attempted to modify the label color of a tab to black, but it seems to be stuck as white. Is this color hard-coded in material-ui? If not, how can I change it? Here's what I've tried: const customStyles = { tab: { padding: '2p ...

Difficulty in adding a simple return to render an array in React for list creation

After establishing a basic object, I noticed that it contained an internal object named "orders" with an array of toppings like "Cheese" and "Bacon". To further explore this structure, I segregated the array and directed it to a function called renderToppi ...

What is the best way to search for documents that have all conditions met within a sub-array entry?

My rolesandresponsibilities collection document is displayed below: [{ "_id": { "$oid": "58b6c380734d1d48176c9e69" }, "role": "Admin", "resource": [ { "id": "blog", "permissions": [ " ...

Leveraging AJAX for seamless PHP execution without page refresh

I have this HTML form: <form class="clearfix" method="POST"> <input name="username" type="text" placeholder="Username:"> <input name="password" type="password" placeholder="Password:"> <textarea name="comment" placeholder="Comment: ...

Is it possible to implement browser-specific CSS in Next JS without affecting other browsers?

Will Next JS automatically add all necessary browser prefixes to CSS styles defined with style jsx, or do I need to write the browser supports manually in my styles when using Next JS? transform: translate(50%, 50%); -webkit-transform: translate(50%, 50%); ...

Discover the secret to easily displaying or concealing the form of your choice with the perfect fields

Greetings! I require assistance in understanding how to hide or display a form. Specifically, I have two forms - studentForm and EmployeeForm. When selected from the dropdown list profileType, I want the corresponding form to be displayed. I am facing an ...

An error message 'module.js:557 throw err' appeared while executing npm command in the terminal

Every time I try to run npm in the terminal, I encounter this error message and it prevents me from using any npm commands. This issue is also affecting my ability to install programs that rely on nodejs. $ npm module.js:557 throw err; ^ Error: Cannot ...

converting JSON to date format in angular

.controller('feedCtrl', ['$scope', '$http', function($scope, $http) { $http.get('items.json').then(function(response) { $scope.items = response.data; $scope.user = localStorage.getItem("glittrLoggedin"); ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

The React MUI Tab component triggers a re-render and clears the states of its child components

In our endeavor to create a Tab Page using React MUI, we aim for each Tab to contain a child component. While there are no issues when adding these child components individually to a page without tabs, problems arise when incorporating them within the Tab ...

Running an express server on localhost with nginx: A step-by-step guide

Is it possible to run the express server using Nginx on localhost? And if so, how can this be accomplished? const express = require('express') const app = express() const port = 3000 app.get('/', (req, res) => res.send('Hello ...

Creating dynamic dropdown menus within a Rails 3 form using Prototype and incorporating database queries

Recently, I've been on the hunt for a seamless method to create dynamic dropdown menus within a form that can be populated with data from a database based on the selection of a previous dropdown. Unfortunately, my search for a suitable Rails 3/prototy ...

I'm confused as to why the icon color isn't changing on the Blogger homepage for each individual user

I'm experimenting with changing the eye color based on visitor count. It works perfectly fine on static posts in my Blogger, but it fails to update the eye color properly on my homepage according to the set numeric values. Instead of displaying differ ...

JavaScript Algorithm for Pyramids

Experimenting with simple algorithms brought me to this code. I'm curious if anyone has a more concise version in JavaScript for displaying a pyramid: const max= 30; let row = 1; for (let i = 1; i < max; i += 2) { console.log(' '.r ...

What is causing my Directive to trigger the error "Error: $injector:unpr Unknown Provider"?

I have been diligently working on updating my Controllers, Factories, and Directives to align with the recommended Angular Style Guide for Angular Snippets. So far, I have successfully refactored the Controllers and Factories to comply with the new style ...