What steps can I take to create a bar that animates in just 1 second using HTML, CSS, and JavaScript?

I'm currently working on a custom progress bar in Javascript that updates every second and then resets.

I attempted to use setInterval() to change the value, but I couldn't get it to work.

Any assistance would be greatly appreciated, thank you!

Below is my code snippet:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .progress {
            position: relative;
            width: 510px;
            height: 60px;
            background: #9cbab4;
            overflow: hidden;
          
        }
        .progress__fill {
            width: 0%;
            height: 100%;
            background: #009579;
            transition: all 0.1s;
        }

        .progress__text{
            position: absolute;
            top: 50%;
            right: 5px;
            transform: translateY(-50%);
            font: bold 20px 'Quicksand', sans-serif;
            color: #ffffff;
        }
    </style>
</head>
<body>
    <div class="progress">
        <div class="progress__fill"></div>
        <span class="progress__text">0%</span>
    </div>
    <script>
        setInterval(function(){
            value++;
        }, 1000);
        function updateProgressBar(ProgressBar, value){
            ProgressBar.querySelector(".progress__fill").style.width = '${value}%'
            ProgressBar.querySelector(".progress__text").textContent = '${value}%'
        }
    </script>
</body>
</html>

Answer №1

Trying to replicate your code, I transformed the progress, progress__fill, and progress__text into ids and changed the

<div class="__" />
to <div id="__" />:

<style>
    #progress {
        position: relative;
        width: 510px;
        height: 60px;
        background: #9cbab4;
        overflow: hidden;
      
    }
    #progress_fill {
        width: 0%;
        height: 100%;
        background: #009579;
        transition: all 0.1s;
    }

    #progress_text{
        position: absolute;
        top: 50%;
        right: 5px;
        transform: translateY(-50%);
        font: bold 20px 'Quicksand', sans-serif;
        color: #ffffff;
    }
</style>

This is how the <div /> looks in my reproduction:

<div id="progress">
    <div id="progress_fill"></div>
    <span id="progress_text">0%</span>
</div>

In the <script>, there was no variable for value so I added one and initialized it as zero: let value = 0; then appended it with '%'.

I utilized window.setInterval and replaced the querySelector with document.getElementById due to the aforementioned modifications.

Here's what the script tag now looks like:

<script>
 let value = 0;
 window.setInterval(function() {
   if (value != 100) {
     value++;
     document.getElementById("progress_fill").style.width = value + '%';
     document.getElementById("progress_text").textContent = value + '%';
   }
 }, 1000);  
</script>

I added an if (value != 100) statement to halt the process when it reaches 100.

Hopefully, this explanation is beneficial! Below is a link to my code snippet for reference: https://jsbin.com/xiwiyew/5/edit?html

Answer №2

After studying your example, I decided to make some adjustments and experiment a little with the code. The main issue was that you forgot to call the updateProgressBar() function within your interval, causing it not to work properly. The revised code should be self-explanatory. Feel free to reach out if you have any questions.

Here is my updated code. You can also choose to include the two lines within the update function and move them directly into the interval function. Additionally, the function no longer has a limit and will continue beyond 100% if left unchecked for long enough. I hope this clarifies things for you.

        value = 0;
        setInterval(function() {
            value++;
            updateProgressBar(value);
        }, 1000);

        function updateProgressBar(value) {
            document.querySelector(".progress__fill").style.width = value + "%"
            document.querySelector(".progress__text").innerHTML = value + "%"
        }

Based on your code, it seems like you may be new to coding. My advice would be to write out or describe what you want in plain language first, and then try to translate that into your code. For instance, specify that you want a progress bar with an incrementing value every second (handled by the interval function). Breaking down complex logic into separate functions can also improve readability and ease of understanding.

Answer №3

To begin with, it's important to recognize that variables are bound by scope limitations, meaning you can extract the value from your innerHTML and update it in each function call. This approach allows you to obtain real-time values without the need for global storage.

Below is a functional code snippet demonstrating this concept:

setInterval(function () {
  const progress__text = document.querySelector(".progress__text");
  const progress__fill = document.querySelector(".progress__fill");
  if (progress__text && progress__fill) {
    let value = parseInt(progress__text.innerHTML.split("%")[0]);
    if (value === 100) {
      progress__fill.style.width = "0%";
      progress__text.innerHTML = "0%";
    } else {
      progress__fill.style.width = ++value + "%";
      progress__text.innerHTML = ++value + "%";
    }
  }
}, 100);
.progress {
  position: relative;
  width: 510px;
  height: 60px;
  background: #9cbab4;
  overflow: hidden;
}

.progress__fill {
  width: 0%;
  height: 100%;
  background: #009579;
  transition: all 0.1s;
}

.progress__text {
  position: absolute;
  top: 50%;
  right: 5px;
  transform: translateY(-50%);
  font: bold 20px "Quicksand", sans-serif;
  color: #ffffff;
}
<body>
  <div class="progress">
    <div class="progress__fill"></div>
    <span value="0" class="progress__text">0%</span>
  </div>

</body>

Answer №4

This method may not provide precise timing for animations, but it is straightforward to implement

const animation = {
  duration: 2, // length of animation in seconds
  steps: 60,
  counter: 0,
  incrementCounter() {
    this.counter += ((1 / this.duration) * (this.steps / 1000) * 100);
    this.counter = Math.min(this.counter, 100)
  }
}

const draw = setInterval(updateAnimation, animation.steps);

function updateAnimation() {
  animation.incrementCounter();
  document.querySelector(".progress__fill").style.width = animation.counter + '%'
  document.querySelector(".progress__text").textContent = animation.counter + '%'
  if (animation.counter === 100) {
    animation.counter = 0;
    clearInterval(draw)
  };
}
.progress {
  position: relative;
  width: 510px;
  height: 60px;
  background: #9cbab4;
  overflow: hidden;
}

.progress__fill {
  width: 0%;
  height: 100%;
  background: #009579;
  transition: all 0.1s;
}

.progress__text {
  position: absolute;
  top: 50%;
  right: 5px;
  transform: translateY(-50%);
  font: bold 20px 'Quicksand', sans-serif;
  color: #ffffff;
}
<div class="progress">
  <div class="progress__fill"></div>
  <span class="progress__text">0%</span>
</div>

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

Is there a way to prevent users from copying data or switching tasks when using my program or website?

Is it feasible to develop a website or application for Windows desktop machines that can remain focused until the user completes a specific task? For instance, if my YYY app/website is open and I require the user to input some text, I want to restrict the ...

Number Stepper Reverse

Could the HTML5 number stepper be reversed so that pushing down increases the number and vice versa? In Response to any 'Why?' inquiries: Consider batting order in sports like cricket or baseball. As you move down the order, your batting positio ...

Trouble with targeting a specific css class

Can someone help me with a CSS issue I'm experiencing? Here is my code: <div class='test'> <div>test 1</div> <div>test 2</div> </div> <div class='test'> <div>test 3&l ...

adjusting the width of an HTML table cell

I'm struggling with the code below: <table> <thead> <th class='1'>Date</th> <th class='2'>Start Time</th> <th class='3'>End Time </th> <th class='4 ...

Display additional input field using Jquery when text is entered in the textbox

Is there a way to display the input field #f_past_data when the text field #f_past_farmaco is filled out? The field #f_past_farmaco is for entering text. I attempted the following solution but it did not work as expected. $('label[for=f_past_data], ...

Fade in/out or apply opacity to a three.js object

I'm working on a graphical web project using three.js. I have many circles scattered like this. https://i.sstatic.net/y4FN8.png I'm curious if the opacity of objects can be reduced as the distance between the object and camera increases (fade ...

Creating consistent image sizes using Bootstrap or pure CSS styling

I've been attempting to create 6 images that are all responsive and the same size. I've tried using just CSS and also tried using bootstrap cards, but I can't seem to achieve the desired result. I've experimented with flexbox, grids, s ...

Display the html content within a <div> element by leveraging the power of jQuery

Can someone help me with displaying the HTML contents from a dropdown menu button link to a <DIV>? I would appreciate if you could provide a sample page for reference. Thank you in advance :) ...

What is the process for adding elements to the parent elements that have been selected using getElementsByClassName?

Here is the JSP code snippet I'm working with: <% while(resultSet1.next()){ out.println("<p class='comm'>"); out.println(resultSet1.getString("answer_content")); ...

Tips for showcasing content with full width within a bootstrap container

Creating a carousel slider with CSS has been quite successful on Chrome, Firefox, and IE. Check out how it looks below: https://i.sstatic.net/u49Yc.png To make the slider fill up the screen within its container, I applied some tricks like this: margin-l ...

Tips for showing more rows by clicking an icon within an Angular 2 table

When I click on the plus (+) button in the first column of each row, only one row expands. How can I modify it to expand multiple rows at a time? Thanks in advance. <div> <table class="table table-striped table-bordered"> <thead> ...

Troubleshooting auth error with Android and nativescript-plugin-firebase

I am currently utilizing this plugin in my application: https://github.com/EddyVerbruggen/nativescript-plugin-firebase Unfortunately, when using my real device on a 3G network, I encounter the following error: auth/network-request-failed Thrown if a netw ...

What is the proper way to utilize "three.module.js"?

I am currently learning how to utilize modules and decided to start with a simple example. However, I encountered an issue where the script does not want to run. I must be missing something crucial, but I can't seem to figure out what it is. I have tr ...

How can multiple functions be grouped and exported in a separate file in Node.js?

Is there a way to consolidate and export multiple functions in nodejs? I want to gather all my utility functions in utils.js: async function example1 () { return 'example 1' } async function example2 () { return 'example 2' } ...

Incorporate CSS styling from a separate .css file into a material component

Just starting out with material UI. I have a css file that looks like this: .bgItem { font-size: 14px; } My component setup is as follows: <MenuItem key={status.Id} value={status.Value} classes={css.bgItem}> {status.Description} </Men ...

How about placing one element above another? What sets apart using the margin property versus the position property for achieving this effect?

As I pondered the concept of stacking context, a question arose in my mind. Through my readings, I learned that by not applying any CSS properties that create a stacking context (such as position), it is possible to stack elements on top of each other usin ...

The data from the method in the Vue.js component is not displaying as expected

Currently diving into Vue.JS (2) and exploring the world of components. My current challenge involves using a component within another component, grabbing data from a data method. Here's what I have so far: HTML <div id="root"> <h1> ...

javascript the debate between inline and traditional registration

Hey there, I'm a JavaScript beginner and currently learning about inline vs. traditional registration. I've managed to get code block 1 (inline) working perfectly fine, but unfortunately, code block 2 (traditional) isn't cooperating. Can som ...

Implementing promises in Node JS Express

I am new to promises and trying to understand how they function. Here are my initial questions: When a request is handled in a route function, does it wait for all promises? Does using a promise or callback create a new scope where execution continues ...

Instructions on how to use WebClient in C# to download an image and retrieve it from an ASPX page using JavaScript

I have been searching for solutions to this question everywhere, but none of them seem to work for me. The goal is to download an image from the internet using an aspx page. I want to call the aspx page from JavaScript, retrieve the data, and display it i ...