0

Assume I have the following array:

var myarray = [1, 2, 3, 4, 5]

What is the cleanest way using Javascript/CSS3 to make it such that onpage load, each element in the array is shown in a box/div with a red background color on the page? Usually I would just do:

for(var i = 0; i < myarray.length; i++) {
   bodyelement.append("<div class="box">"+myarray[i]+"</div>");
}

The issue is, it is super fast and they all just show up instantaneously without any real "effect".

Though how do I make them "sequentially" animate in as it is appended? Say, for example, the box would animate say from a overly big box and shrink down to the size of the actual div, or fade in gradually. Can this be done with CSS3 only or is there javascript required? How can I create this effect?

Setsuna
  • 2,081
  • 7
  • 32
  • 50
  • In theory you could use CSS animations to achieve the effect you want. You could animate height/width and potentially top/left (or, preferably, just transform) to have the boxes "expand down" to size. See here for more info: http://www.w3schools.com/css/css3_animations.asp – dlev May 11 '14 at 02:31
  • How about using CSS, and in your loop you can just add a class to each element. Timeout each one based on 'i' to stagger the animations. – Zack Argyle May 11 '14 at 03:51
  • @Zack Could you demonstrate this? – Setsuna May 11 '14 at 13:30

2 Answers2

1

Here is an example of what I described in the comments. JSFIDDLE.

Basically you use css transitions, and add a class to each element after a certain period of time.

(function() {
  var elements = document.querySelectorAll("#test div");

  for (var i = 0; i < elements.length; i++) {
     load(elements[i], i);   
  }

  function load(elem, i) {
    setTimeout(function() {
        elem.classList.add("load");
    },50 * i);
  }
}());

CSS

#test div {
  -webkit-transition: opacity 2s ease-in;
     -moz-transition: opacity 2s ease-in;
      -ms-transition: opacity 2s ease-in;
       -o-transition: opacity 2s ease-in;
          transition: opacity 2s ease-in;
}

#test div.load {
  opacity: 1;
}
Zack Argyle
  • 8,057
  • 4
  • 29
  • 37
0

This FIDDLE may get you started.

JS

var fadeintime = 500;

animatediv();

function animatediv()
{
    var number = 0;
    var interval = setInterval(function() { 
                             var divid = $("#div" + number);
                             divid.animate({opacity: "1"}, fadeintime);
                             number++; 
                          if(number > 4) clearInterval(interval);
                   }, 1000);

}

Based on THIS.

Community
  • 1
  • 1
TimSPQR
  • 2,964
  • 3
  • 20
  • 29