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

"An error occurs when attempting to clear Rad Grid data with javascript: htmlfile: Invalid argument thrown

Hello, I am currently developing an ASP.NET application. I am facing an issue where I need to clear the data in a Rad grid upon button click using JavaScript. The code snippet that I have attempted for this is as follows: document.getElementById(&a ...

Declaring an array that holds Angular components in Angular 11: What's the best approach?

I'm trying to implement a feature in my Angular component where I can create a list that displays content from other components. My current approach involves declaring an array that contains references to different Angular components: import { Compone ...

What is the reason for not displaying the various li elements on my webpage?

Here is the code snippet export default function DisplaySearchResults({ results }) { var arr = Object.entries(results) console.log(arr) return ( <div> Here are the search results : <ol> {arr.map((va ...

Assign Monday as the selected day of the week in the MUI Datepicker 6

I am currently using version 6 of the material ui Datepicker and I am trying to configure it so that the week starts on Monday. import React from "react"; import { DatePicker as DatePickerDestop } from "@mui/x-date-pickers/DatePicker"; ...

AngularJS Gallery Showcase

Trying to showcase a collection of videos in a modal using angular.js, I decided to implement the solution from . However, I encountered difficulty in integrating my scope variables into the "html5gallery" class. <div class="html5gallery" data-skin="ho ...

jquery activating the toggle function to switch between child elements

I'm facing a challenge where I can't use .children() in this scenario, as it won't work since the elements aren't technically children. Here's the snippet of HTML that I'm working with: <p class="l1">A</p> ...

Adaptive component transformation

Hey there, I'm having some trouble figuring this out... I need help with making sure that the element identified by the red rectangle in the images moves in alignment with the containers below, regardless of the screen size. I want to create a respon ...

Can you guide me on implementing CSS Houdini in Next.js?

Exploring the world of CSS Houdini in my Next.js project has been quite an adventure. After successfully installing the necessary CSS Houdini package and css-paint-polyfill using yarn, I decided to follow the webpack guidelines provided at . Below is a sn ...

Error message: Uncaught TypeError - The function 'send' is not recognized in the Ajax new Request

When I called my ajax function, I encountered the following error: Uncaught TypeError: ajaxGetData.send is not a function Here is my code: <button onclick="myFunc()" class="btn btn-default">Click</button> <div id="getRes"></div> ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

Is there a beginner's pack or trial version available for utilizing TypeScript with IBM Cloud Functions / OpenWhisk?

While working on developing actions in IBM Cloud Functions, I have been primarily using Node.js / Javascript and Python for coding. However, I haven't come across specific instructions on how to incorporate TypeScript into IBM Cloud Functions. I am c ...

The functionality of the Bootstrap carousel is not functioning properly in the Firefox browser

I attempted to customize the bootstrap carousel in order to create a simple content slider. After reviewing two events in the bootstrap documentation and utilizing animate.css for animation, I found that Chrome and Internet Explorer displayed the animation ...

Leverage the power of AJAX and PHP to securely save comments for future

I have coded a JavaScript function that uses POST and GET methods to send comments from an input field and retrieve them when the page reloads. However, I am unsure of how to handle the data after it is sent in order to save it and access it again later. E ...

Unforeseen issues arise when using material ui's Select component in conjunction with 'redux-form'

I am encountering an issue with a 'redux form' that includes a Select component from the latest material-ui-next. import { TextField } from 'material-ui'; <Field name="name" component={TextField} select > <MenuIte ...

Learn how to toggle multiple class elements with jQuery, and how to hide the ones that have

This is an example of my HTML code: <h4 class="list-group-item-heading"> @Model.Customer.FirstName @Model.Customer.LastName wrote: <span class="right"><span class="icon-file padding-right link"></span></span> </h4& ...

Mistakes in serializing arrays for javascript in an ajax request

I am trying to send an array of JavaScript objects in an Ajax call. This is how I create my array: var itemsToEdit = []; $(".editedItem[value='true']").closest("tr").each(function() { var itemToEdit = { id: $(this).find(".i ...

Is there a way to alter the variant or background of a clicked button exclusively through reactjs? If so, how can I make it happen?

My goal is to change the variant of a Material UI button from outlined to contained or simply change its background color when it is clicked. I am unable to use the onFocus property due to conflicts with another component. Here is my current method, but ...

Having trouble accessing the value of an object within a nested array object

Looking for a way to extract the object value from a nested array object using JavaScript? If the sourcecountry matches the country in the object, it should return the corresponding payment service. Here is what I have attempted: function getValue(source ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

Combination of words & design having "background-image:url"

Currently utilizing Thymeleaf within a Spring Boot project, the following code initializes an image in the center of the screen (sourced from this .html ): <div class="col-lg-9 image_col order-lg-2 order-1"> <div class="single_product_image"& ...