The progress bar seems to be malfunctioning

Need help with my progress bar, it's not working properly. Can someone assist me?

var x = document.getElementById("p_bar");

for(var i = 0; i < 100; i++) {
  var wid;
  wid=1;
  if(wid == 800)
    break;
  else
    wid+=8;
  x.style.width=wid+"px";
}

 document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont {
    width: 800px;
    height: 30px;
    background-color: cornsilk;
    position: relative;
}

#p_bar {
  width: 8px;
  height: 30px;
  background-color: red;
  position: absolute;
}
<div id="cont">
    <div id="p_bar"></div>
</div>
<p id="write"></p>

Answer №1

const progressBar = document.getElementById("p_bar");
let widthCount = 1;

const interval = setInterval(function(){

  if(widthCount <= 800){
      widthCount += 8;
      progressBar.style.width = widthCount + "px";
  } else {
    clearInterval(interval);
  }

}, 1000);


 document.body.style.background = "#" + ((1 << 24) * Math.random() | 0).toString(16);
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;

}
<div id="cont">
<div id="p_bar"></div></div>
<p id="write"></p>

To observe a dynamic progress bar, utilize the setInterval() method.

If you solely rely on a for loop, there won't be any visual animation visible.

This is due to the rapid computation speed of computers, which only allows you to witness the final outcome of the for loop.

Answer №2

If you're interested, I decided to rewrite it using functions:

var x = document.getElementById('p_bar');
var container = document.getElementById('cont');
var write = document.getElementById('write');

var containerWidth = container.offsetWidth;
var currentWidth = x.offsetWidth;

var updateProgress = function (step, interval) {
currentWidth = Math.min(currentWidth + step, containerWidth);
write.innerHTML = Math.floor((currentWidth / containerWidth) * 100) + '%' // Display percentage
x.style.width = currentWidth + 'px'
if (currentWidth < containerWidth) setTimeout(function () {
updateProgress(step, interval)
}, interval)
}

updateProgress(8, 300) // Initiates progress

document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
}
<div id="cont">
<div id="p_bar"></div>
</div>
<p id="write"></p>

Answer №3

It's a bit unclear what kind of behavior you are looking for. Typically, the size of the bar changes based on certain application events (in this example, timeouts are used). Here is a sample code that might give you some insight:

 document.body.style.background = "#"+((1<<24)*Math.random()|0).toString(16);
 
 var setBarWidthInPercent = function(barId, value){
 var bar=document.getElementById(barId);
  bar.style.width = value+"%";
 } 
 
 setTimeout(function(){
 setBarWidthInPercent("p_bar",10)
 },500)
 
 setTimeout(function(){
 setBarWidthInPercent("p_bar",50)
 },1500)
 
 setTimeout(function(){
 setBarWidthInPercent("p_bar",100)
 },3000)
#cont{
width: 800px;
height: 30px;
background-color: cornsilk;
position: relative;
}
#p_bar{
width: 8px;
height: 30px;
background-color: red;
position: absolute;
-webkit-transition: width 1s ease-in-out;
    -moz-transition: width 1s ease-in-out;
    -o-transition: width 1s ease-in-out;
    transition: width 1s ease-in-out;
}
<div id="cont">
<div id="p_bar"></div></div>
<p id="write"></p>

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

Steps for creating interconnected datepickers in jQuery with month and year selection:To create a dependent datepicker with month and year selection using

The JSFiddle I currently have is not functioning as expected. When the user directly selects the end-date, it does not restrict the start-date in this particular fiddle. It should change once the user directly changes the end-date. The functionality works ...

The placement of the content in the Grid system seems to be off-kilter, not aligning properly with Bootstrap standards

I am facing an issue with the logo and navbar layout in my design. The design has 3 columns for the logo and 6 columns for the navbar, as shown in this image: https://i.stack.imgur.com/RpmJm.jpg However, when I run the code, they do not appear in the cor ...

Create shorter nicknames for lengthy reference names within the ng-repeat loop

Is it possible to assign an alias to a long reference name in ng-repeat? Currently, I have 2 complex objects where one acts as a grouped index for the other. Although the ng-repeat template code is functioning correctly, it's getting hard to read and ...

Customize Column Headers in Handsontable: A Quick Guide

Is there a way to customize the appearance of column headers in handsontable? I have provided a jsfiddle example to showcase my current progress. While I am able to format the first row of data and change the column titles, I am facing difficulty in forma ...

Understanding the Significance of this Regular Expression

I need assistance with regular expressions as I am not very familiar with them. The issue I am facing is related to a jQuery dynacloud plugin that stops working when a regex match occurs in my code. Can someone please help me understand what this regex mat ...

Creating a CSS animation to slide a div outside of its container is

I currently have a flexbox set up with two adjacent divs labeled as DIV 1 and DIV 2. By default, both DIV 1 and DIV 2 are visible. DIV 2 has a fixed width, occupying around 40% of the container's width. DIV 1 dynamically adjusts its width to ac ...

Double clicking on a row value in a Bootstrap table

Struggling to retrieve the row value after a double click in a bootstrap table. Unfortunately, every attempt returns 'undefined'. Snippet of my code: $('#table').on('dbl-click-row.bs.table', function(field, value, row, $el) ...

Struggling to break free from the confines of an overflow-hidden container in swiperjs due to

I have a slider that utilizes swiperjs and I want to incorporate a dropdown menu within each swiper-slide. However, I've encountered an issue where the dropdown menu is unable to escape the root container due to the positioning constraints. For a dem ...

Creating functional dropdown menus with popperjs in the latest Bootstrap version 5

Currently, I am attempting to implement dropdown menus in Bootstrap 5. According to my research, this feature requires Popper.js integration, but I am uncertain of the correct way to include it in my Laravel project that utilizes Laravel Mix. I have made ...

The JavaScript syntax dollar sign

I am currently studying a JavaScript source code and it's my first time writing JavaScript. I find some of the syntax confusing. <script id="source" language="javascript" type="text/javascript"> $(function () { window.onload=function() ...

Google Maps fails to load when triggered by the jQuery show() function

One issue I'm facing is that the Google Map is not loading after the show() function is called in jQuery. Initially, I use display:none to close a division on page load. After some research, I found out that it can be resolved by using google.maps.eve ...

Shifting elements within Phoria.js

I'm currently working on a game where a ball bounces and falls into a randomly placed bin. I'm wondering if there's a way for the ball to jump and land based on the dynamic coordinates of the bin. If I have knowledge of the direction and dis ...

Tips for implementing a settimeout function in a VUEJS script

I'm currently working on my first Vue.js application and I'm facing an issue with the initial data upload in the script. After modifying the data received from a database call, I encounter an error during the page's initial load which resolv ...

Error: The `Field` component encountered a failed prop type validation due to an invalid prop `component` after upgrading to MUI version

Encountered an error when migrating to Material ui v4 Failed prop type: Invalid prop component supplied to Field. in Field (created by TextField) This error points to the redux form field component export const TextField = props => ( <Field ...

The webpage Page.php is failing to display the newly added content

I have a collection of logos on my homepage (index.php) in WordPress, and they are positioned at the bottom just as I intended. However, these logos do not appear on all pages. Even if I add the exact same code to the page.php file in the exact position, ...

Tips for setting discrete mapper style in cytoscapejs?

Currently, I am defining the style of cytoscape.js through CSS and converting it to JSON format using this resource. My goal is to implement a discrete mapper for styling. It's similar to the scenario discussed in How to use a descreteMapper like on c ...

An issue has been identified where the checked selection feature is not functioning correctly for CSS selections

Is there a way to change the border color of a label when a checkbox is checked using CSS selectors? Here's an example of what I have tried: label{ width:36px; height:36px; padding:9px; border:1px solid gray; border-radius:36px; } #check ...

Steps for importing jQuery typings into TypeScript:1. First, install the jQuery

I've searched for similar questions, but haven't found one that matches my issue. Can someone help me figure out what to do next? In my Visual Studio project, I used package.json to download jquery typings into the node_modules folder: { "ver ...

The issue of a false value not being correctly matched in Jasmine is causing problems

Currently, I am utilizing the following code to evaluate an element with aria-checked="false". expect((accessPolicyPage.listSelectAll).getAttribute("aria-checked")).toEqual("false"); The output is presenting as Expected [ 'false' ] to equal &ap ...

Similar to `util.inspect` in Node.js, Deno also has a function

Is there a utility function in Deno that can stringify an Object or primitive similar to Node.js util.inspect? For instance, if I have a JSON object in Node.js and want to display its contents: > m = {k1:'v1', k2:'v2'} { k1: ' ...