Implementing a Timer on a Bootstrap Progress Bar Using JavaScript

I am currently working on a timer with a progress bar. The timer itself is functioning properly, but I am facing an issue with syncing the progress bar with the timer. I am utilizing the bootstrap progress bar for this project. If I remove the 'bar' variable from the function, the timer works perfectly fine, however, when the progress bar is included, it stops working. Any suggestions or recommendations would be greatly appreciated. Thank you :)

function startTimer(duration, display, bar) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        bar.css('width', minutes + '%');

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var minutes = 60 * 15,
    display = document.querySelector('#time');
    bar = document.querySelector('#progressBar');
    startTimer(minutes, display, bar);
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<div class="progress mx-auto mb-2" style="max-width: 300px;">
    <div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span id="time">15:00</span>

Answer №1

To set the width of the progress bar, use the property bar.style.width instead of the .css() method which is a part of jQuery.

To achieve the correct percentage for the progress bar, calculate the total time and the remaining time in seconds, then adjust the bar's width accordingly.

function startTimer(duration, display, bar) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);
        
        var totalSeconds = 15 * 60
        , remainingSeconds = minutes * 60 + seconds
        
        bar.style.width = (remainingSeconds*100/totalSeconds) + "%";
        
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var minutes = 60 * 15,
    display = document.querySelector('#time');
    bar = document.querySelector('#progressBar');
    startTimer(minutes, display, bar);
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<div class="progress mx-auto mb-2" style="max-width: 300px;">
    <div class="progress-bar bg-success" role="progressbar" id="progressBar" style="width: 100%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<span id="time">15:00</span>

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

Methods for removing cookie during logout with Express and Passport JS?

I have been struggling to delete cookies upon logout but haven't had any luck so far. I searched online and came across two methods: Setting a new expiration date for the cookie res.cookie('connect.sid', '', {expires: new Date(1 ...

Ways to dynamically activate an anchor tag's click event using JavaScript?

I'm having trouble triggering an already written click event for an anchor tag using JavaScript. Can someone help me figure out how to do this? I have the following anchor tag: <a id="memberid">Data Member</a> <script> $("#memb ...

Utilizing the input element to modify the font color of the title upon clicking the button

I've been honing my skills in Angular and facing an issue with altering the font color of a variable called title. I'm struggling to figure it out. Take a look at the code snippet from tools.component.ts: [...] title: string = 'Add note ...

Empty data passed to Highcharts xAxis labels formatter callback function

I am new to using Highcharts and I am trying to utilize the xAxis.labels.formatter function to generate labels. However, I am facing an issue where the formatter function is running with empty data. Interestingly, when I click on the legend, the data gets ...

The React.useCallback hook in Cube.js is missing a dependency, specifically 'pivotConfig'. This could potentially cause unexpected behavior in the application

After multiple attempts at creating a straightforward dashboard using Cube.js with Windows 10 and MySQL version 8, I am feeling frustrated. Initially, I experimented with a JavaScript backend, struggled through the installation process for days, then attem ...

Substitute empty spaces and organize the text layout

I'm struggling to figure out how to substitute the whiteSpace in an aggregate request using MongoDB and also how to remove a specific part of a string (most likely requiring regex). Here's an example of my document: { "_id": "57dfa5c9xxd76b ...

The functionality of scrolling in Angular Material tabs is not functioning properly

I have encountered a challenge while working with angularjs material design. The md-scroll functionality is not working as expected for scrolling up and down, even though it works fine for left and right scrolling. In a tab with a table view, the vertical ...

Utilizing Ajax and Jquery to dynamically adjust CSS properties, dependent on data from a specific MySQL row

I've been working on a system to automatically update a Scene Selection page whenever a new number is added to the permission table in Mysql. The PHP for the login and retrieving the number from the members table is working fine. My issue now lies wi ...

Error: Unhandled Exception - Invalid syntax, unrecognized value: #

Encountering an error in jQuery with a .click() event, as seen in Firebug. Using the latest version 1.3.2 (min), the click triggers an $.ajax() request for a form on my website. Researching online, found information on "%" or "[@]" as unrecognized expressi ...

Connect the HTML link component tag to a component that is passed through the constructor

I have recently started learning about Angular and TypeScript. Within my AppComponent HTML file, I include another component using the code <app-listpost></app-listpost> In the TypeScript file, I import the ListPostComponent into my AppCompon ...

CSS3 Transition effects are applied immediately to duplicated elements

My dilemma lies in applying CSS3 Transitions to elements by introducing a new class. Markup <div id="parent"> <div class="child"> </div> </div> CSS .child { background: blue; -webkit-transition: background 4s; ...

Firebase Lists versus Objects: A comparison of data structures

Seeking some clarification regarding Firebase lists. I'm attempting to access multiple lists within a single object in order to iterate through them. The structure of the object is as follows: user : { playlists: {}, // List 1 joined: {}, ...

The jQuery click event appears to be malfunctioning

Attempting to create a basic calculator using jQuery, the code seems straightforward but nothing is happening when executed. It's as if the JavaScript file isn't linked properly. Below is the jQuery code snippet: function addNumber(num){ ...

Using MongoDB to group by the difference in dates and retrieve the hour value

Currently, I am working on an application and I require some information from my database: I have a model called "traitement" which includes a user, The "traitement" model has a start date and an end date, both in Date format, allowing MongoDB to use ISO ...

Prevent the dropdown from closing after clicking on a href link

Is there a way to ensure that my dropdown remains open even after a page reload? I'm looking for a solution where clicking on an item(href) within the dropdown will keep it open after redirection. I've tried using the jQuery method called stopPr ...

In next js, the component exceeds 100% overflow when padding is added

https://i.sstatic.net/W30tk.png Hey there, I've been encountering some issues with next js and styled-components. I have a parent component (sc-hgRfpC lbMBdR) with a width of 400px, and swap-div-5 with a width: 100%. However, when I add padding: 12px ...

The CSS float puzzle - text alignment dilemma

Recently, I created a simple float-based banner with tiles which you can see here on jsfiddle. However, I encountered a major issue with centering text in each tile. My goal is to have all the "Sample text" content centered both horizontally and vertically ...

Using jQuery to retrieve the values of two distinct sliders and executing a specific mathematical operation

I have two sliders with their own values and properties: https://i.stack.imgur.com/3OZqr.gif My goal is to retrieve the values of these two sliders and calculate a result that will be displayed next to the interest label. The calculation formula is: poun ...

Using Bootstrap to Implement Special CSS Styles for Various Devices

Is there a way to implement specific CSS rules for different screen sizes using bootstrap? For example, on medium screens (md), can we set an element's left-margin to 10px and have it be 100px on small screens (sm)? Any guidance would be appreciated. ...

The AngularJS modal is sending back the results before updating the parent scope

When launching a modal from my web page, I am updating an array passed from the parent. However, when closing the modal and sending back the updated results, the parent scope object is also being updated. If the user decides not to update and cancels the ...