How to change style with setTimeout in Javascript

Viewed 489

(?) I want to change my class name 'box' from opacity '0' to opacity '1.0' like an animation or fade in every sec 1000ms, 2000ms. 3000ms,

(X) But I don't want to do something like this code but appears fade in like this Code on jsfiddle and not fade in at the same time like this Code on jsfiddle.

var DivB = document.getElementsByClassName("box");
setTimeout(function(){DivB[0].style.opacity = "1"}, 1000);
setTimeout(function(){DivB[1].style.opacity = "1"}, 2000);
setTimeout(function(){DivB[2].style.opacity = "1"}, 3000); 

(/) I want to make It appears with the delays 1000,2000,3000 with javascript look shorter like using var 'i' to javascript like this .. Code on jsfiddle.

var DivB = document.getElementsByClassName("box"); 
var i;

function myFade(){
for (var i=0; i<DivB.length; i++){
setTimeout(function(){DivR[i].style.opacity="1"}, i*1000)}
}

myFade();
4 Answers

You can add transition: all 1s; to the box CSS from one of the code examples you posted:

var DivB = document.getElementsByClassName("box");

setTimeout(function(){DivB[0].style.opacity = "1"}, 1000);
setTimeout(function(){DivB[1].style.opacity = "1"}, 2000);  
setTimeout(function(){DivB[2].style.opacity = "1"}, 3000); 
.box { display:inline-block; position:relative; opacity:0; 

transition: all 1s;}
<div class='box'>1</div><br/>
<div class='box'>2</div><br/>
<div class='box'>3</div><br/>

You're looking for setInterval

var DivB = document.getElementsByClassName("box");
var divIndex = 0;
var interval = setInterval(() => {
  DivB[divIndex].style.opacity = "1";
  divIndex++;
  if (divIndex === divB.length - 1) clearInterval(interval);
} , 1000)

Basically, this will fire every one second, setting the opacity of divB[divIndex] to '1'. divIndex itself increments every interval as well. After all the DivB elements are processed, the interval will be cleared.

You can do this :

var DivB = document.getElementsByClassName("box");

function myFade() {
  for (let i = 0; i < DivB.length; i++) {
    setTimeout(() => {
      DivB[i].style.opacity = "1"
    }, i * 1000)
  }
}

myFade();
.box {
  display: inline-block;
  position: relative;
  opacity: 0;
}
<div class='box'>1</div>
<div class='box'>2</div>
<div class='box'>3</div>

I would suggest you to read the difference between var and let specially when using in loops with setTimeout and setInterval

Hope this helps !

Try it:

function fadeElementsProgressive(className, timePerElement = 1000) {
 const divs = document.getElementsByClassName(className);
  
  for(let i = 0; i < divs.length; i++) {
   setTimeout(() => {
     divs[i].style.opacity = 1;
    }, i * timePerElement)
  }
}

fadeElementsProgressive('box');
.box { display:inline-block; position:relative; opacity:0; }
<div class='box'>1</div><br/>
<div class='box'>2</div><br/>
<div class='box'>3</div><br/>

This will create a function that get a class name and execute a fade.

Related