Home > Software engineering >  JS button function increase size by increment of percentage
JS button function increase size by increment of percentage

Time:06-27

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 >
  <div ></div>
</div>
<button onclick="increaseProgress()">Click to increase</button>

CodePudding user response:

@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 >
  <div ></div>
</div>
<button onclick="increaseProgress()">Click to increase</button>

  • Related