Raj
Raj

Reputation: 107

Add to width using setInterval

I am trying to add to the width of the element everytime the setInterval function is invoked

function setProgress(){
  var bar = document.getElementById('progress-bar');
  var width = 20;
  bar.style.width += width + 'px';

  //console.log(bar.style.width);
}

window.onload = function(){
  setInterval(setProgress, 10);
}

I tried using parseInt(), but everytime I console.log() to the window i see the same width. My end goal is for the width to increase by 20

Upvotes: 0

Views: 1075

Answers (4)

Anies Ahamed
Anies Ahamed

Reputation: 1

var width = 0; function setProgress(){ var bar = document.getElementById('bar'); width+= 20; bar.style.width = width + 'px'; console.log(bar.style.width); if(width==200){ width=0; } } window.onload = function(){ setInterval(setProgress, 1000); }

Upvotes: -1

Alexander Bell
Alexander Bell

Reputation: 7918

Make width a global var, like shown below:

var width = 0;
function setProgress(){
     var bar = document.getElementById('progress-bar');
     width+= 20;
     bar.style.width += width + 'px';
     //console.log(bar.style.width);
}
window.onload = function(){setInterval(setProgress, 10);}

Also, you should specify the max width to prevent the progress bar moving outside the working area (for example, modifying the increment line: if(width<500) {width+= 20;} else {return;}).

Alternatively, you can use your original solution by adding couple more statements, namely: removing the "px" unit from style property bar.style.width, then parsing it (converting to Number), then incrementing it and then adding "px" (otherwise, "+" operator will cause a concatenation of strings with output like: 20px20px, 20px20px20px, etc). Such alternative solution will slow down the process and put additional load on CPU (thus, it's not recommended).

Hope this may help. Best regards,

Upvotes: 1

Oriol
Oriol

Reputation: 288310

The problem is that width returns a string with units.

Instead, consider storing the number of pixels in a variable:

var bar = document.getElementById('progress-bar'),
    width = parseFloat(getComputedStyle(bar).width);
setInterval(function() {
    width += 20;
    bar.style.width = width + 'px';
}, 10);

var bar = document.getElementById('progress-bar'),
    width = parseFloat(getComputedStyle(bar).width);
setInterval(function() {
  width += 20;
  bar.style.width = width + 'px';
}, 200);
#progress-bar {
  background: #0f0;
  display: inline-block;
}
<div id='progress-bar'>Progress bar</div>

Upvotes: 0

dfsq
dfsq

Reputation: 193261

You need to remove px part from width style and then cast string to number before incrementing it:

function setProgress(){
  var bar = document.getElementById('progress-bar');
  var width = 20;
  bar.style.width = Number(bar.style.width.replace('px', '')) + width + 'px';

  //console.log(bar.style.width);
}

Upvotes: 2

Related Questions