Austin737
Austin737

Reputation: 776

Expand the width of an element with a setTimeOut loop

I am trying to create a simple javascript animation that will expand the width of an element from 0px to a specified width. Although this is probably a pretty elementary problem for some, I just can't seem to figure out what I am doing wrong. Instead of the loop running and expanding the div as desired I am only able to expand the div by repeatedly firing the function manually.

Fiddle

Current js code:

  var el = document.getElementById('h');
var btn = document.getElementById('button1');
var oswidth = el.offsetWidth;
var target_width = 100;


btn.onclick = function grow() {
    var loop = setTimeout('grow(\'' + el + '\')', 20);
    if (oswidth < target_width) {
        oswidth += 5;
    } else {
        clearTimeout(loop);
    }
    el.style.width = oswidth + 'px';
 }

And as always, thank you in advance!

Upvotes: 0

Views: 842

Answers (4)

balajisoundar
balajisoundar

Reputation: 571

Try this code.fiddle-https://jsfiddle.net/L8kLx7d2/

  var el = document.getElementById('h');
  var btn = document.getElementById('button1');
  var oswidth = el.offsetWidth;
  var target_width = 100;
  var loop;

  function grow() {
     if (oswidth < target_width) {
         oswidth += 5;
   } else {
      clearInterval(loop);
   }
   el.style.width = oswidth + 'px';
}
btn.onclick=function(){
 loop=setInterval(grow, 1000)};

Upvotes: 1

Lajos Arpad
Lajos Arpad

Reputation: 76692

There are three solutions. The first is using recursive setTimeout:

function grow(time) {
    if (oswidth < target_width) {
        oswidth += 5;
        el.style.width = oswidth + 'px';
        setTimeout(function() {grow(time);}, time);
    }
}

The second is to use setInterval as described in the answer of K K.

The third is my personal favorite, using the transition css attribute.

Upvotes: 0

Sean
Sean

Reputation: 4515

Try this:

var el = document.getElementById('h');
var btn = document.getElementById('button1');
var oswidth = el.offsetWidth;
var target_width = 100;

btn.onclick = function grow() {
    if (oswidth < target_width) {
        oswidth += 5;
        el.style.width = oswidth + 'px';
        setTimeout(grow, 20);
    }
}

I'll leave it to you to puzzle over the differences.

Upvotes: 0

K K
K K

Reputation: 18099

You can call the grow function in setInterval

JS:

var el = document.getElementById('h');
  var btn = document.getElementById('button1');
  var oswidth = el.offsetWidth;
  var target_width = 100;


  function grow() {
      var loop = setTimeout('grow(\'' + el + '\')', 20);
      if (oswidth < target_width) {
          oswidth += 5;
      } else {
          clearTimeout(loop);
      }
      el.style.width = oswidth + 'px';
  }
  setInterval(grow, 1000);

Demo: http://jsfiddle.net/lotusgodkk/jeq834de/1/

Upvotes: 0

Related Questions