How can I specify the exact width for Bootstrap 3 Progress Bars?

I have a single page that displays all my files in a table format, and I also have the count of open and closed files.

My goal is to represent the percentage of closed files using a progress bar. The width of the progress bar should change based on this percentage.

My question is: How can I dynamically set the width of the progress bar to display the calculated value? I am utilizing Bootstrap 3 for my project.

If anyone could provide some guidance in the right direction, I would greatly appreciate it.

Answer №1

// total files
let totalFiles = 42;

// closed files
let closedFiles = 30;

// locate progress bar element
const progressBar = document.querySelector('.progress-bar[role="progressbar"]');

// find remaining progress bar element
const remainingBar = document.querySelector('.progress-bar[role="remaining"]');

function onFileChange() {
  // calculate percentage
  let percentage = Math.min(Math.max(Math.floor(closedFiles / totalFiles * 100), 0), 100);
  // calculate remaining percentage
  let remaining = 100-percentage;

  // apply percentage to the progress bars
  progressBar.style.width = percentage + '%';
  progressBar.innerText = percentage + '%';
  remainingBar.style.width = remaining + '%';
  remainingBar.innerText = remaining + '%';
}

// make changes based on file simulation
document.querySelector('#totalFiles').addEventListener('change', e => {
  totalFiles = e.target.value;
  onFileChange();
});
document.querySelector('#closedFiles').addEventListener('change', e => {
  closedFiles = e.target.value;
  onFileChange();
});

onFileChange();
.progress-bar[role="remaining"] {
  background-color: #888;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="progress">
      <div class="progress-bar" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">55%</div>
      <div class="progress-bar" role="remaining" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">45%</div>
    </div>
  </div>


  <!-- Simulatet file change controls -->
  <form>
    <div class="form-group">
      <label for="totalFiles">Total Files</label>
      <input type="number" class="form-control" id="totalFiles" placeholder="Total Files" value="42">
    </div>
    <div class="form-group">
      <label for="closedFiles">Closed Files</label>
      <input type="number" class="form-control" id="closedFiles" placeholder="Closed Files" value="30" />
    </div>
  </form>

</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

JavaScript issues in FireFox and Internet Explorer when using JQuery

I have developed a PHP GD image for generating captcha images, saved as image.php. Each time it creates a unique captcha image. Inside the signup.php file: <img alt="" src="image.php"> <input type="button" id="btn" value="cannot read captcha"&g ...

Vue: add a CSS class to products when they are in the shopping cart

As I delve into creating a shopping cart using laravel + vue, I am encountering a major obstacle related to vue's functionality. Within my cart component, the goal is to allow users to effortlessly add or remove products by simply clicking. When a pr ...

Tips for refreshing the Vuex store to accommodate a new message within a messageSet

I've been working on integrating vue-socket.io into a chat application. I managed to set up the socket for creating rooms, but now I'm facing the challenge of displaying messages between chats and updating the Vuex store to show messages as I swi ...

Using both Bing and Google geolocation services due to compatibility with Internet Explorer

Hey there! I'm currently working on implementing geolocation functionality into my project, and it's been smooth sailing except for one hiccup - Internet Explorer doesn't seem to play nice with Google Maps and prefers Bing instead. Has anyon ...

Improving file reading and parsing efficiency with fast random access using csv-parse in Node.js

I recently encountered a challenge while working with the csv-parser library in node for parsing large CSV files. The files I work with can range from 50,000 to 500,000 lines or even larger. My task involved performing computations on this data and then su ...

In what way can the jQuery .each() function make use of the index as a variable?

Consider the jQuery .each() function, which comes with a useful feature. For example: $('.element').each(function(index){ console.log(index); }); Here, you can access the index of the currently selected element using the "index" variable. ...

Nextjs google places autocomplete not providing accurate suggestions

I'm attempting to utilize Google autocomplete to retrieve the names of mosques specifically in the United Kingdom. However, the data I am receiving is global and not limited to mosques. Here is my code: import axios from "axios"; export def ...

Event cancellation received from IncomingMessage

I have a simple express server running on Node with versions 4.13.3 and 4.2.3, respectively. //initialization code app.put('/', function(req, res) { req.on('close', function() { console.log('closed'); }); req.on( ...

Is it recommended to create model classes in React components?

Within the realms of React, the Flux architecture is utilized. According to https://reactjs.org/docs/thinking-in-react.html, React operates with two distinct models - namely, the state and props. There are recommendations provided for model management in ...

Surprising outcome encountered while trying to insert an item into a list

I'm a bit puzzled by the current situation where: let groupdetails = { groupName: "", }; const groupsArray = []; groupdetails.groupName = 'A' groupsArray.push(groupdetails) groupdetails.groupName = 'B' groupsAr ...

Establishing numerous websocket connections within a singular application

I am looking to conduct load testing on our websocket service. Is there a method to establish multiple websocket connections from one workstation? My attempt with npm ws and websocket modules in conjunction with NodeJS was successful for a single connecti ...

What is the best way to showcase specific rows with Vue.js?

After fetching data from a specific URL, I am looking to display only the 2nd and 4th rows. { "status": "ok", "source": "n", "sortBy": "top", "articles": [ { "author": "Bradford ", "title": "friends.", ...

Ensure each list item is directly aligned when swiping on a mobile device

Looking to make a simple horizontal list swipeable on mobile devices with tabs that snap from tab to tab, activating the content for the active tab immediately. The desired effect is to swipe directly from one tab to the next without having to click separ ...

Creating collections in a Hashtable style using JavaScript

Creating a collection in JavaScript can be done in the following way: Start by initializing an empty collection with var c = {}; Next, you can add items to it. After addition, it will look like: { 'buttonSubmit': function() { /* do some work * ...

jQuery - final slide not triggering interval, causing animation malfunction

I am working on creating a slider using multiple divs instead of images. I have a total of 3 divs, and while the first two transition smoothly as intended, the third div seems to fly away too quickly - it briefly appears and then snaps back to the first di ...

Revamping the Bootstrap admin template

Is there a way to customize this Bootstrap 3 admin template? https://getbootstrap.com/docs/3.3/examples/dashboard/ I want to make some changes like removing the top fixed navbar and shifting everything up by 50px (as defined in dashboard.css). However, I ...

Modifying the dimensions of media:thumbnail in Blogger's RSS Feed

I came across this post, but it seems like there have been updates in the past 4 years regarding how thumbnails are generated for Blogger posts. I've attempted various methods, but so far none of them have been successful. If anyone could assist me in ...

Why does a black model appear when loading a GLTF model with materials?

I am currently attempting to load a 3D model in glb format. Below is the code snippet: Expected Outcome: Image Current Outcome: Image var renderer = new THREE.WebGLRenderer(); renderer.setSize(1000, 1000); renderer.setPixelRatio(window.devicePixelRati ...

Is there an alternative to the jQuery :contains selector?

How can I choose an option from a drop-down menu based on its text value? When I execute the following code: var desiredText = "Large"; $("#size option:contains(" + desiredText + ")").attr('selected', 'selected'); it ends up selecting ...

Show just three items simultaneously

I am currently working on a quote generator and I want to add a feature that allows me to display a specific number of quotes at a time. I attempted to use map for this purpose, but encountered an error stating it's not a function. Currently, the gene ...