Home > front end >  Javascript addEventListener Multi function
Javascript addEventListener Multi function

Time:08-03

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>

CodePudding user response:

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 >
  <div ></div>
</div>

CodePudding user response:

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>

  • Related