1

I want to make a progress bar, if you look at my code I am trying each time I click Next changing progress.style.width, for example, first time 33.33% and next 66.66% and last time 100%.

this is my first time asking a question in Stackoverflow sorry if I'm too new!

const next = document.querySelector("#next");

const progress = document.querySelector(".progress");

next.addEventListener("click", function() {
  progress.style.width = "33%";
});
.progress {
  height: 10px;
  background: blue;
  width: 0%
}
<button id="next">Next</button>

<br/>
<br/>
<div class='progress'></div>

2 Answers 2

1

You need to maintain some state for the current progress. I would recommend a separate variable but you could also parse the current progress.style.width value

const next = document.querySelector("#next");
const progress = document.querySelector(".progress");

next.addEventListener("click", () => {
  const current = parseFloat(progress.style.width || "0");
  const width = `${Math.min(current + 100/3, 100)}%`;
  progress.style.width = width;
});
.progress-container {
  border: 1px solid;
  width: 200px;
  height: 1rem;
}
.progress {
  height: 1rem;
  width: 0;
  background-color: blue;
}
<button id="next">Next</button>

<div class="progress-container">
  <div class="progress"></div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Put .progress in a bigger container then define a value outside of function. Increase that value incrementally within the function. See closures

const next = document.querySelector("#next");

const progress = document.querySelector(".progress");

let ratio = 0;

next.addEventListener("click", function() {
  ratio += 33.33;
  ratio = ratio > 100 ? 100 : ratio;
  progress.style.width = ratio+'%';
});
.fullbar {
  background: yellow;
  width: 50vw;
  border: 2px inset blue;
}
  
.progress {
  height: 10px;
  background: blue;
  width: 0%
}
<button id="next">Next</button>

<br/>
<br/>
<section class='fullbar'>
<div class='progress'></div>
</section>

2 Comments

Stops before 100, oh no!
That .01% is essential! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.