Creating a progress bar feature using local storage in JavaScript

Is there a way to retain the progress of the countdown timer with a progress bar on page reload? Here is an example of what I am trying to achieve: https://codepen.io/Rudchyk/pen/qNOEGj

<div id="progressBar">
                <div class="bar"></div>
            </div>
            <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
            <script>
                var seconds = {$timer_limited->sec}; // 10000
                $(document).ready(function () {
                    function progress(timeleft, timetotal, $element) {
                        
                        var progressBarWidth = timeleft * $element.width() / timetotal;
                       
                        $element.find('div').animate({ width: progressBarWidth }, 500);
                        if(timeleft > 0) {
                            setTimeout(function() {
                                progress(timeleft - 1, timetotal, $element);
                            }, 1000);
                        }
                    };

                    progress(seconds, seconds, $('#progressBar'));
                });
            </script>
            <style>
                #progressBar {
                    width: 100%;
                    height: 4px;
                    background-color: #DDDFE2;
                }
                #progressBar div {
                    height: 100%;
                    line-height: 22px;
                    width: 0;
                    background-color: #D03637;
                }
            </style>

Any suggestions on how to save and restore the progress when the page is reloaded?

Answer №1

function trackTime() {
    var progressBarWidth = remainingTime * $progressBar.width() / totalTime;
    $filler.animate({ width: progressBarWidth }, 500).html(Math.floor(remainingTime/60) + ":"+ remainingTime%60);
    
    remainingTime--
    localStorage.setItem('timeLeft', remainingTime)
    if(remainingTime < 0) {
        clearInterval(timerInterval)
    }
};

const $progressBar = $('#progressBar')
const $filler = $progressBar.find('div')

const totalTime = 600
var remainingTime = localStorage.getItem('timeLeft') ?? totalTime

const timerInterval = setInterval(trackTime, 1000)

I made some adjustments to your code, including renaming variables for clarity. One key addition is the utilization of localStorage to store and retrieve the remaining time information. This ensures that the clock is synchronized even upon page refresh.

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

Unable to modify the value of an object variable generated from a query in JavaScript, ExpressJS, and MongoDB

Here is the code snippet I've been working on: let addSubmissions = await Submission.find({"type": "add-information"}, (err) => { if(err) { console.log(err) req.flash('error', 'No "add submissions" were found&apo ...

Using Javascript and Node.js to send a JSON request

While browsing through this particular question, I came across a method in node.js to distinguish between html requests and json requests: app.get('/route', function (req, res) { if (req.is('json')) res.json(data); else if (req ...

Warning from React 17: Unexpected presence of <a> tag inside <div> tag in server-rendered HTML

I've checked out the existing solutions and still can't seem to make it work. components/NavBar.tsx import { Box, Link } from "@chakra-ui/react"; import { FunctionComponent } from "react"; import NextLink from "next/link ...

Adjusting the background hue of the 'td' element within an ajax request

When I press a button, an ajax call is triggered below. In this call, I append 'td' elements with values to a table. Specifically, on the line ''</td><td>' + result[i].preRiskCategory +', I am attempting to change ...

axio. to retrieve the information stored in an alternate document

Seeking assistance in utilizing API data in a separate file. I have three files: api.jsx import axios from 'axios'; export const api = (url, data) => { const { path, method } = url; let result ={}; axios({ method: ...

What is the best way to navigate users to a different page using AJAX upon receiving a successful response from PHP?

I am currently using a JavaScript function that is functioning correctly. It retrieves all error messages from the PHP file and displays them in a span with the ID "resto" without any issues. However, I now have a requirement where if the PHP file return ...

Best method for loading data into a new MongoDB database?

I currently have a Docker container set up locally with MongoDB and an express node server. Can anyone suggest the best method to add new data to this setup? 1) Should I utilize the command line interface (CLI)? 2) Is it better to use Mongoose for this ta ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

Remove array element by key (not numerical index but string key)

Here is a JavaScript array that I am working with: [#ad: Array[0]] #ad: Array[0] #image_upload: Array[0] 13b7afb8b11644e17569bd2efb571b10: "This is an error" 69553926a7783c27f7c18eff55cbd429: "Yet another error" ...

Customizing an image with personalized text and then sending it to a server using a combination of javascript and

Looking for a way to add text to an image saved on the server, then save the edited image back to the server. I've heard using canvas is the best approach, but struggling to find the specific solution I need. ...

Shifting divs to different positions upon clicking

I am currently working on a project where I have three divs in a container positioned next to each other. My goal is to make them change their positions when clicked. For example, clicking on the left div should move it to the center position. Here is my p ...

The attempt to run 'readAsBinaryString' on 'FileReader' was unsuccessful. The first parameter is not the expected type 'Blob'

I am currently working on parsing an xls file. You can find the file by clicking on the following link: However, I am encountering an error that says: 'Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of ...

I'm looking for guidance on effectively utilizing filter and map within the reducers directory to manipulate the workouts objects

I am encountering an issue while trying to send delete and update requests for the workout object. The error message indicates that the filter function is not compatible as it's being applied to an object instead of an array. Here is the snippet of co ...

In JavaScript, provide a boolean response to a callback function from a separate function

Working with the jQuery validate plugin involves utilizing a submitHandler callback function. This function determines whether the form submission should proceed based on its return value - false will prevent submission, while true will allow it to go thro ...

Tips on keeping Bootstrap Modals out of your browsing history

Imagine this scenario A visitor lands on Page A, clicks through to Page B, and then engages with a link that triggers a modal (code provided below) <a href="mycontent.html" data-target="#modal_xl" data-toggle="modal" data-backdrop="static">Click me ...

The issue persists as AJAX data and text box data are not being saved simultaneously

I need assistance with an Ajax setup. I am trying to pass the screenwidth information along with a user input value from a text box to a PHP page. However, I am encountering issues as the only value being passed is from the textbox and the other one is sho ...

Exploring ways to connect my React application with a node backend on the local network?

On my MacBook, I developed a react app that I access at http://localhost:3000. In addition, I have a nodejs express mysql server running on http://localhost:5000. The issue arises when I try to open the IP address with port 3000 in the browser of my Window ...

Tips for organizing information within a table

I have been developing a tool that allows users to enter a username, and then I display the data fetched from GitHub related to that particular user. Although each cell in the table is sortable, they all seem to sort data based on the first cell. When I cl ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

prevent unnecessary duplicate database queries for generating metadata in the upcoming 13 or 14 instances

In the latest updates, version 13 and 14 of Next introduced the usage of the generateMetadata function as the preferred method to define all page metadata. However, a drawback of this approach is that because of the separation of logic, fetching data base ...