Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Pawel Klosinski
Pawel Klosinski
6,932 Points

How to loop through and display divs with classes for 5 seconds?

Hi guys,

I am building a simple flashcard app with Ruby on rails and have got following problem. I want to hide all divs when the page is loaded and gradually display each one for 5 seconds. So first div is visible for 5 seconds, then the it disappears and the next div is displayed. This continues until the final div disappears.

The HTML has got following structure:

<div id="content">
   <div class="flashcard">
      <p>flashcard 1</p>
   </div>
   <div class="flashcard">
      <p>flashcard 2</p>
   </div>
   <div class="flashcard">
      <p>flashcard 3</p>
   </div>
</div>

I think I need JavaScript which I do not know well. Can you help?

2 Answers

Steven Parker
Steven Parker
231,110 Points

If you're going to want to do things like this, perhaps you might want to take some JavaScript courses!

But just for fun, I did this one:

const cards = document.getElementsByClassName("flashcard");
let n = 500;  // initial delay{
for (let i in cards) {
  let card = cards[i];
  card.style.display = "none";
  setTimeout(_=> {
    card.style.display = "";
    setTimeout(_=> card.style.display = "none", 5000);  // display time
  }, n);
  n += 5500;  // display + delay
}
Pawel Klosinski
Pawel Klosinski
6,932 Points

Hello Steve, thank you very much, your code works well.

Absolutely, I will take JavaScript course, I just do not want to mix everything at the same time :)

Thanks again for your help, kind regards.