Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS button function increase size by increment of percentage

As you can see from my code, the progress bar doesn’t increase by even units. I need the container to remain responsive but the progress bar to increase by even units.

function increaseProgress() {
  var progressBar = document.querySelector(".progress-bar")
  var currWidth = progressBar.clientWidth;
  progressBar.style.width = currWidth + 10 + "%";
}
.progress-container {
  width: 100%;
  height: 20px;
  outline: solid 2px #ccc;
  border-radius: 20px;
}

.progress-bar {
  width: 0;
  height: inherit;
  background: blue;
  border-radius: 20px;
}
<div class="progress-container">
  <div class="progress-bar"></div>
</div>
<button onclick="increaseProgress()">Click to increase</button>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@evolutionxbox makes a good suggestion in the comments. It is far more flexible than this manual approach you’re taking.

However, if you are still looking for a fix for your current code, here is one:

First, you need to find out how much the total container width is. In other words, finding out how much "10 percent" is.

Once you find that out, you can simply increase the current bar width by a tenth the container width. We also want to prevent it from increasing beyond 100%.

function increaseProgress() {
  var progressBar = document.querySelector(".progress-bar")
  var progressContainer = document.querySelector(".progress-container")

  var barWidth = progressBar.clientWidth;
  var containerWidth = progressContainer.clientWidth;

  if (barWidth >= containerWidth) return;

  progressBar.style.width = (barWidth + containerWidth / 10) + "px";
}
.progress-container {
  width: 100%;
  height: 20px;
  outline: solid 2px #ccc;
  border-radius: 20px;
}

.progress-bar {
  width: 0;
  height: inherit;
  background: blue;
  border-radius: 20px;
}
<div class="progress-container">
  <div class="progress-bar"></div>
</div>
<button onclick="increaseProgress()">Click to increase</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading