Create a JavaScript button that increases a progress bar value by 1 and adjusts its width style by 10 units

Here is the code for managing a progress bar using JavaScript:


function getProgress() {
    return document.getElementById("progressbar").getAttribute("aria-valuenow");
}

function setProgress(value) {
    document.getElementById("progressbar").setAttribute("aria-valuenow", value);
    document.getElementById("progressbar").setAttribute("style", "width: " + value + "%");
    document.getElementById("progressbar").innerHTML = value + "%";
}

function increment() {
    var i = getProgress();
    if (i < 100) {
        i++;
        setProgress(i);
    } else {
        alert("Download Finished!");
    }
}

function decrement() {
    var d = getProgress();
    setProgress(d - 1);
}

function resetButton() {
    setProgress(0);
}

To change the values and width style when clicking the increment button, make sure to call the `increment()` function. The HTML part contains buttons for various operations on the progress bar.

Answer №1

There were some issues with the functions for getProgress and setProgress. In the getProgress function, you were incorrectly using return multiple times, so we have corrected it to just return the value. Additionally, in the setProgress function, there was a syntax error in setting the width attribute. Below is the updated working version of the code.

function getProgress() {
  var progressValue = document.getElementById("progressbar").getAttribute("aria-valuenow");
  return progressValue;
}

function setProgress(value) {
  document.getElementById("progressbar").setAttribute("aria-valuenow", value);  
  document.getElementById("progressbar").setAttribute("style", "width: " + value + "%;");
  document.getElementById("progressbar").innerHTML = (value + "%");
}

function increment() {
  var currentValue = getProgress();
  if (currentValue < 100) {
    currentValue++;
    setProgress(currentValue);
  } else {
    alert("Download Finished");
  }
}

function decrement() {
  var currentProgress = getProgress();
  setProgress(currentProgress - 1);
}

function resetButton() {
  var resetValue = getProgress();
  setProgress(resetValue = 0);
}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

  <title>Progress Bar</title>

</head>

<body>
  <!-- Container -->
  <div class="container">

    <h1>This Progress bar is animated using <br>JavaScript!</h1>
    <br>

    <!-- Div For Progress Bar -->
    <div class="progress">
      <div class="progress-bar progress-bar-striped" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="progressbar">0%</div>
    </div>

    <br>
    <!-- Buttons -->
    <button type="button" class="btn btn-primary" onclick="increment()">Increment</button>
    <button type="button" class="btn btn-dark" onclick="resetButton()">Reset</button>
    <button type="button" class="btn btn-success" onclick="decrement()">Decrement</button>
    <button type="button" class="btn btn-warning" onclick="">Start Auto Progress!</button>
    <button type="button" class="btn btn-danger" onclick="">Stop Auto Progress!</button>

    <p id="value"> </p>
    <!-- End of Container -->
  </div>

  <!-- Optional JavaScript -->
  <!-- jQuery first, then Popper.js, then Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
  <script src="Assignment4.js"></script>
</body>

</html>

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

Creating a fetcher that seamlessly functions on both the server and client within Nextjs 13 - the ultimate guide!

My Nextjs 13 frontend (app router) interacts with a Laravel-powered backend through an api. To handle authentication in the api, I am utilizing Laravel Sanctum as suggested by Laravel for SPAs. This involves setting two cookies (a session and a CSRF token) ...

Efficiently pinpointing the <div> element with precision using jQuery

I am building an interactive quiz for users of my app. The questions are table based, and can be answered "yes," "no," or "maybe." If the user answers "no" or "maybe," I would to slide open an informational panel that lives beneath the table. Here is the ...

Using Node.js to establish communication between HTML and Express for exchanging data

I am faced with a challenge involving two pages, admin.hbs and gallery.hbs. The goal is to display the gallery page upon clicking a button on the admin page. The strategy involves extracting the ID of the div containing the button on the admin page using J ...

Is it possible to utilize the package.json "resolutions" field to replace lodash with lodash-es?

Is it possible to use resolutions in a similar manner as dependencies, but with a different package? I'm specifically curious if this can be done with NPM or Yarn. "resolutions": { "lodash": "npm:lodash-es@^14.7.x" ...

Please explain this ES6 syntax to me: Using a colon after a function call

While exploring the documentation for a flux store in React, I came across an example that caught my attention. import {ReduceStore} from 'flux/utils'; class CounterStore extends ReduceStore<number> { getInitialState(): number { ret ...

When the button is clicked, the ng-click event will trigger the addClass function, but only on the second click

My bootstrap alert has this structure: <div id="errorAlert" class="alert col-md-6 col-md-offset-3 fadeAlert" ng-if="itemExistsAlert"> <button type="button" class="close" data-dismiss="alert">&times;</button> <p>{{alertM ...

Can $event be transferred from cshtml to Vue.component?

I am facing an issue when trying to pass an event into my Vue component. No matter what method I try, I keep getting a "TypeError: Cannot read property 'preventDefault' of undefined" error. Here is the code snippet for my Vue component: Vue.com ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

Isolating a type as a constant in Typescript within a .js file?

Within my .js configuration files, I have a tsconfig containing the property checkJs: true. A library called Terser includes the following type options: ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 Despite setting ecma: 2017 in my configuration file ...

Eliminating characteristics and rejuvenating the component

I have divs on my webpage that I want to keep hidden until a specific element is clicked. When trying to hide them, I encountered three options: visibilty: hidden - I didn't like this because the hidden div still took up space in the layout. displa ...

Removing redundant names from an array using Typescript

My task involves retrieving a list of names from an API, but there are many duplicates that need to be filtered out. However, when I attempt to execute the removeDuplicateNames function, it simply returns an empty array. const axios = require('axios&a ...

Tips for Sending Information to the Current Page Using JQuery

I am attempting to send the form data back to the same location as the form itself. The code needs to: Trigger the click action for #submit Retrieve data from #email, #selection1, and #selection2 Hide the form #form Show the data in #email, #selection1, ...

Ways to delay the inner function's output?

Need help with making a function return only after its inner function is called. See below for the code snippet - function x() { function y() { // Inner function logic } return result; // This should be returned only after function y is ca ...

how to properly position an image using javascript

I have two tilesheet images and I have successfully rendered them, but I am struggling to figure out how to place the character in front of the map. https://i.stack.imgur.com/n1a3Q.png I have placed these images in two different JavaScript files. This i ...

The cannon-es program experiences crashes every time two Convex polyhedrons collide with each other

Currently, I'm working on implementing a dice roller using three.js and cannon-es. Everything runs smoothly when there's only one dice, rolling against the ground plane in a satisfactory manner. However, the trouble arises when I add a second di ...

The require statement in Vue.js is failing to function dynamically

Having trouble dynamically requiring an image in Vue.js and it's not functioning as expected <div class="card" :style="{ background: 'url(' + require(image) + ')',}"> export default { data() { return { ...

Tips for sending attributes to jQuery autocomplete

I'm facing a major issue with implementing a jquery autocomplete feature, and JavaScript isn't my strong suit. Currently, I'm using the jquery.auto-complete plugin available at: https://github.com/Pixabay/jQuery-autoComplete, which is an up ...

Avoiding the reset of a variable when utilizing state in React

Is it possible to have a variable in React that remains unchanged during rendering without using context or moving it up the components hierarchy? import React, {useState,useMemo,useRef} from 'react' const Component=()=>{ const [state,setS ...

How can I loop the keyframe animation across various elements of an SVG file simultaneously?

After creating an animation using CSS and SVG, I am experiencing different parts of it animating in and out. My goal is to have the animation start from the top once it's finished. There are multiple keyframes involved since I'm animating variou ...

Exploring the journey of History.js and Same-Origin Policy leading to HTTPS encryption

Utilizing history.js, I am attempting to push a state change from an HTTP site like: http://www.example.com/some/resource ...to a secure site (payment page), such as: https://www.example.com/payment/for/some/resource However, Safari is throwing thi ...