Reputation: 755
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
Reputation: 21116
You have to use a setTimeout or setInterval to delay/animate the incremental changes.
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
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:
x
contains a string, but you are using it as a number.'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