Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to appendChild with Animation in javascript?

Tags:

javascript

css

I cant use Jquery (just javascript). I have a simple array of images that I find a random index values and appendChild(MyRandomImages) (3 images all at once) to the page. I need it to be appended with a transition animation ease-in 0.5s, ease-in 1s, ease-in 1.5s.

images = ["image/1.png",
          "image/2.png",
          "image/3.png",
          "image/4.png",
          "image/5.png",
          "image/6.png"];

var img = document.createElement("img");
var img1 = document.createElement("img");
var img2 = document.createElement("img");  

var randomVal = Math.floor(Math.random()*images.length);
var randomVal1 = Math.floor(Math.random()*images.length);
var randomVal2 = Math.floor(Math.random()*images.length);

img.src = images[randomVal];
img1.src = images[randomVal1];
img2.src = images[randomVal2];


var result = document.getElementsByClassName("result");
result[0].appendChild(img);
result[1].appendChild(img1);
result[2].appendChild(img2);

So result[0].appendChild(img) needs somehow to have preventDefault() and be animated into the scene, I tried invoking css3 animation by adding a new class that animates it. So if class:

.result {
width:0;
height:0;}

And I did el.classList.add("animate"); where el is result class:

.animate{
-webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  -ms-transition: 0.5s;
  -o-transition: 0.5s;
  transition: 0.5s;
    width: 300px;
    height: 300px;
}

but it didnt work. and I had the logical problem of how applying three classes to each one since I need them to be appended at different times (0.5, 1, 1.5s).

I would very much like to somehow invoke a css3 animation to do this and use no Jquery.

Thanks In advance.

like image 737
AliR Avatar asked Sep 02 '25 04:09

AliR


1 Answers

To append images sequentially you can do:

  • use JS's .forEach(element, index) that:
  • creates a random image
  • appends the image to DOM
  • use setTimeout(()=> {/*job*/}, time * index ) where time*index will result in N timeouts like: 0, 500, 1500 .... having time set to 500ms and the job is to add your .animate class.

const images = [
  "//placehold.it/300x300/0bf",
  "//placehold.it/300x300/f0b",
  "//placehold.it/300x300/bf0",
  "//placehold.it/300x300/0fb",
  "//placehold.it/300x300/b0f",
  "//placehold.it/300x300/fb0",
];

const createImg = (el, i) => {
  const img = document.createElement("img");
  img.src = images[~~(Math.random() * images.length)];
  el.appendChild(img);
  setTimeout(()=> img.classList.add("animate"), i*500);
}


document.querySelectorAll(".result").forEach(createImg);
body {
  display: flex;
}

.result img{
  max-width: 100%;
  transform: scale(0);
  transition: 0.5s;
}

.result img.animate{
  transform: scale(1);
}
<div class="result"></div>
<div class="result"></div>
<div class="result"></div>
like image 129
Roko C. Buljan Avatar answered Sep 05 '25 01:09

Roko C. Buljan