Toping
Toping

Reputation: 755

Js animated width w/o jquery

Like i said in title, im trying to animate a element width with js:

function floatMenu(rewidth){
if(rewidth.className == ''){ 
   rewidth.className = 'open'; x = rewidth.style.width;
   x = x.slice(0, -2);
   while(x < 190){
      x++; rewidth.style.width = x;
   }
} else {
   rewidth.className = '';x = rewidth.style.width;
   x = x.slice(0, -2);
   while(x > 30){
      x--;  rewidth.style.width = x;
   }
};

}

tried setTimeout already.

Ty for the answers

it ends up with the last value, not incrementing step by step.

Upvotes: 1

Views: 97

Answers (2)

Louis Ricci
Louis Ricci

Reputation: 21116

You have to use a setTimeout or setInterval to delay/animate the incremental changes.

http://jsfiddle.net/qWtGk/6/

window.slide = function(rewidth, amt, min, max) {
 var x = rewidth.style.width;
 x = parseInt(x.replace(/[^\d]/g, ""));
 var evt = setInterval(function() {
  x += amt
  if(x < min) x = min;
  if(x > max) x = max;
  rewidth.style.width = x + "px";
  if(x == min || x == max) clearInterval(evt);
 }, 50);
}

Upvotes: 1

Guffa
Guffa

Reputation: 700910

You can't animate anything by setting styles within a loop, as nothing is changed in the user interface until you exit the function and return control to the browser. Use setInterval to run code at a set interval.

Also:

  • The variable x contains a string, but you are using it as a number.
  • You forgot to add 'px' when setting the style.

Code:

function floatMenu(rewidth) {
  var handle, x;
  if (rewidth.className == ''){ 
    rewidth.className = 'open';
    x = parseInt(rewidth.style.width.slice(0, -2));
    handle = window.setInterval(function(){
      if (x < 190) {
        x++;
        rewidth.style.width = x + 'px';
      } else {
        window.clearInterval(handle);
      }
    }, 50);
  } else {
    rewidth.className = '';
    x = parseInt(rewidth.style.width.slice(0, -2));
    handle = window.setInterval(function(){
      if (x > 30) {
        x--;
        rewidth.style.width = x + 'px';
      } else {
        window.clearInterval(handle);
      }
    }, 50);
  };
}

Upvotes: 2

Related Questions