Home > Enterprise >  Is there a better way to display each element of a content wrapper after a certain time?
Is there a better way to display each element of a content wrapper after a certain time?

Time:01-09

I would like to display each div inside the content-wrapper after a certain time.
I currently use the el1, el2, el3, ... classes to achieve this goal. But some of my content-wrappers have multiple elements, which makes it less elegant as each class has to be unique. Is there a better way to achieve this, for example by using the el class common to each sub-element of the content-wrapper div.

I currently have this html and js.

<div >
   <div >1</div>
   <div >2</div>
   <div >3</div>
</div>

JS

function display_elt(elt_class, time){
   setTimeout(function(){
       document.querySelector(elt_class);
   }, time)
}

var time_int = 0; 
divs = ['elt1', 'elt2', 'elt3'];
for (let i = 0; i < divs.length; i  ) {
  time_int   = 0.5;
  function display_elt(divs[i], time_int);
} 

A solution with CSS, Javascript or JQuery will be welcome.

CodePudding user response:

just using pure plain CSS

all the code is commented.


useful documentations:

* {
  /* this is a css variable */
  --delay: 0.5s;
}

.el {
  /* hidden by default */
  opacity: 0;
  /* shorthand -> name duration timing-function fill-mode */
  animation: fadeIn 0.5s linear forwards;
  /* the real trick is here */
  animation-delay: calc(var(--delay) * var(--i));
  /*el1 -> 0.5s * 0 = 0 */
  /*el2 -> 0.5s * 1 = 0.5s */
  /*el3 -> 0.5s * 2 = 1s */
}

@keyframes fadeIn {
  from {
    /* is not visible*/
    opacity: 0;
  }
  to {
    /* is visible */
    opacity: 1;
  }
}
<div >
  <!-- 0 -->
  <div style="--i: 0;" >1</div>
  <!-- 1 -->
  <div style="--i: 1;" >2</div>
  <!-- 2 -->
  <div style="--i: 2;" >3</div>
  <!-- if more elements, increase the --i css variable for next elements -->
</div>

CodePudding user response:

There are a couple things wrong with your code. First, you seem to be selecting the element but you aren't doing anything with it.

Second, you have several syntax errors in your code: incorrect use of function keyword, reference to wrong variable, etc.

Here are the corrections you need to make:

function display_elt(elt_class, time){
   setTimeout(function(){
       document.querySelector('.' elt_class).hidden = false; // make the element NOT hidden
   }, time)
}

var time_int = 0; 
var divs = ['el1', 'el2', 'el3'];
for (let i = 0; i < divs.length; i  ) { // use 'divs.length' (which is 3 not 4)
  time_int   = 0.5;
  display_elt(divs[i], time_int); // call the function with 'divs[i]'
}

and in your html, just set each element to be initially hidden

<div >
   <div  hidden>1</div>
   <div  hidden>2</div>
   <div  hidden>3</div>
</div>
  •  Tags:  
  • Related