Creating a progress bar with blank spaces using HTML, CSS, and JavaScript

Upon running the code below, we encounter an issue when the animation starts. The desired effect is to color the first ten percent of the element, then continue coloring incrementally until reaching 80%. However, as it stands now, the animation appears messy. Assistance in resolving this issue would be greatly appreciated.

My current code snippet:

function loadIt() {
  var elem = document.getElementById("myBar");   
  var width = 1;
  var id = setInterval(frame, 10);
  function frame() {
    if (width >= 80) {
      clearInterval(id);
    } else {
        width++; 
        elem.style.width = width + '%'; 
    }
  }
}
#myElement {
  width: 100%;
  background: repeating-linear-gradient(to right, green, green 10%, transparent 10%, transparent 12%);
}

#myBar {
  width: 0%;
  height: 30px;
  background: repeating-linear-gradient(to right, grey, grey 10%, transparent 10%, transparent 12%);
}
<div id="myElement">
  <div id="myBar"></div>
</div>

<br>
<button onclick="loadIt()">Click ON</button> 

Answer №1

The issue arose from using a percentage-based width for inner divs while the outer div's CSS rule was set in pixels. To resolve this, keep the default outer div CSS rule in pixels and adjust the inner div to work with percentages.

function loadIt() {
      var elem = document.getElementById("myBar");   
      var width = 1;
      var id = setInterval(frame, 10);
      function frame() {
        if (width >= 80) {
          clearInterval(id);
        } else {
          width++; 
          elem.style.width = width + '%'; 
        }
      }
    }
#myElement {
      width: 100%;
      background: repeating-linear-gradient(to right, grey, grey 10px, 
transparent 10px, transparent 15px);
    }

    #myBar {
      width: 0%;
      height: 30px;
      background: repeating-linear-gradient(to right, green, green 10px, 
transparent 10px, transparent 15px);
    }
<div id="myElement">
      <div id="myBar"></div>
    </div>

    <br>
    <button onclick="loadIt()">Click ON</button>

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

Transforming three items into an array with multiple dimensions

There are 3 unique objects that hold data regarding SVG icons from FontAwesome. Each object follows the same structure, but the key difference lies in the value of the prefix property. The first object utilizes fab as its prefix, the second uses far, and t ...

Looking to optimize the JavaScript code for improved performance speed

Is there a more efficient way to avoid writing the same lines of code repeatedly without compromising performance? I've attempted using a for loop to categorize fields as 'mandatory' or 'optional', but it still requires duplicating ...

When the NPM package is imported as a whole, it shows up as undefined. However, when it

I've come across a peculiar issue in my code where importing the textile/hub package in Node.js and then destructuring it later results in an error. However, if I destructure it while importing, the program runs without any issues. Can anyone shed som ...

A guide on how to perfectly center a <ul> element on a webpage

After creating a ul element, I have customized the html and css for my navigation bar: Html: <ul id="list-nav"> <li><a href="Marsrutas.html">Item1</a> </li> <li><a href="Nuotraukos.html">Item2</a& ...

Show the file name in the email signature instead of displaying the image

I'm facing a unique challenge with images in my HTML email signature. Sometimes the images are replaced by their file names on certain email hosts. Interestingly, I can't replicate this error now as the images are displaying correctly again! He ...

Developing Angular dynamic components recursively can enhance the flexibility and inter

My goal is to construct a flexible component based on a Config. This component will parse the config recursively and generate the necessary components. However, an issue arises where the ngAfterViewInit() method is only being called twice. @Component({ ...

Guide to exporting everything within a div as a PDF using Angular 2

When attempting to convert a div with the id "div1" into a PDF using JSPdf in Angular 2, everything seems to be working fine until I try to export it to PDF. Here is my code snippet: <div class="container" id="div1"> <table> <tr> & ...

Actions for HTML form submission to API through proxy link

Currently, the form is functioning properly with this setup <form method="POST" action='http://localhost:3000/newRecord'> However, my goal is to simplify the action attribute to just be action='/newRecord'. In React, I achieve ...

Changing the selection in the Angular Mat-Select dropdown causes the dropdown's position to shift

Issue with dropdown position: The dropdown should display below the select element, but when selecting the second value, it appears on top of the select element. I have removed any relevant CSS to troubleshoot, but the problem persists. See screenshots for ...

Tips for aligning hyperlinks in the navigation bar using CSS3 and HTML5

Struggling to center the links in the navigation bar has been a challenge. I really want those buttons smack dab in the middle of the header bar, but despite trying everything, they stubbornly remain on the left-hand side. .header { overflow: ...

Can you clarify the concept of closures and how they bind the loop counter to the function scope?

I have observed programmers setting up event listeners inside loops, utilizing the counter. The syntax that I have come across is as follows: for(var i=0; i < someArray.length; i++){ someArray[i].onclick = (function(i){/* Some code using i */})(i); ...

Struggling to calculate the total of a property within an array of objects

I'm currently trying to calculate the sum of a specific property within an array object. Although I successfully accomplished this in one component, I am encountering difficulties replicating it in another. The error message being displayed is: this. ...

Utilize Next.js and GSAP to dynamically showcase images upon hovering over the title

I have a dynamic list of titles that I want to enhance by displaying images when hovering over each title. The issue I'm facing is that when I hover over one title, all the images display at once. As a React beginner, I believe the solution should be ...

Having trouble updating the input value in AngularJS?

As I venture into customizing an AngularJS tutorial on a Saturn Quiz, I am transforming it from multiple choice to a fill-in-the-blank quiz. The challenge I face is that the first answer registers as correct or incorrect, but subsequent questions always s ...

A guide on dynamically adjusting image size in ReactJS

Here is the structure I have: img { width: auto; height: 200px; } .cards { display: flex; justify-content: center; margin-top: 2em; width: 80%; flex-wrap: wrap; } .card { margin: 1em; box-shadow: 0 0 6px #000; ...

Creating a scheduled redirect button using JavaScript and another button to cancel it

I'm facing an issue with my code. When the first button is clicked, it redirects the user to a different URL after 10 seconds. However, I'm struggling to make the second button cancel the redirect if pressed before the 10 seconds are up. Despite ...

What is causing my AJAX function to malfunction and throwing an exception for undefined data objects?

I am having trouble with my ajax query in my code. Even though it is returning the required data, it is not displaying properly within the HTML code. I have a common header and footer (PHP) for all other files. Despite my efforts to resolve this issue by s ...

The Bootstrap 3.3 Carousel is stationary and does not rotate

I am facing a challenge with implementing a Carousel using Bootstrap version 3.3.7 on my website. The code snippet is as follows: <!-- Carousel ================================================== --> <div class="row dark-start d-none d-lg-block"&g ...

Checkbox input with alphabetical ordering

I am currently facing an issue with a form that has checkboxes, but the text is not in alphabetical order. While there are plenty of examples for lists, finding examples for checkboxes has been challenging. http://jsfiddle.net/fG9qm/ <form> < ...

NextJS React - WebpackError: Cannot access 'window' before initialization

I'm delving into the world of React and recently completed the "Getting Started" tutorial for NextJs (link), successfully setting up a new project. However, when attempting to import third-party plugins like current-devices or smooth-scrollbar, I enc ...