Hide HTML element based on CSS class after specified duration

Viewed 65

I would like to unhide all elements inside certain class on a webpage according to a chosen time written in the class.

For example:

  • class=".unhide15" should unhide the element after 15 seconds.
  • class=".unhide123" should unhide the element after 123 seconds.

And so on..

I arrived to this code below (it works), but I still can't chose any time I want.

<style>
    .unhide15, .unhide30, .unhide60{
      display:none;
    }
</style>
<script>
setTimeout(function(){
    [].forEach.call(document.querySelectorAll('.unhide15'), function (el) {
        el.style.display = 'block';
    });
}, 15000);

setTimeout(function(){
    [].forEach.call(document.querySelectorAll('.unhide30'), function (el) {
        el.style.display = 'block';
    });
}, 30000);

setTimeout(function(){
    [].forEach.call(document.querySelectorAll('.unhide60'), function (el) {
        el.style.display = 'block';
    });
}, 60000);
</script>

Any thoughts on how to do this?

1 Answers

I would use only one class... Along with a data attribute to hold the desired time.

document.querySelectorAll(".unhide").forEach(function (elem) {
  let delay = parseInt(elem.getAttribute("data-time")) * 1000;
  setTimeout(function () {
    elem.style.display = "block";
  }, delay);
});
.unhide{
  display: none;
}
<div class="unhide" data-time="1">Hello!</div>
<div class="unhide" data-time="3">Hello!</div>
<div class="unhide" data-time="10">Hello!</div>
<div class="unhide" data-time="12">Hello!</div>

=== EDIT

Since you cannot add data- attributes... You can have an array (on the JS side) to do the same thing about time values. Just make sure to have all them... And in order.

// Set a time array for each element (in order)
let time_array = [
  1, 3, 10, 12 // seconds
];

document.querySelectorAll(".unhide").forEach(function (elem, index) {
  let delay = time_array[index] * 1000;
  setTimeout(function () {
    elem.style.display = "block";
  }, delay);
});
.unhide{
  display: none;
}
<div class="unhide">Hello!</div>
<div class="unhide">Hello!</div>
<div class="unhide">Hello!</div>
<div class="unhide">Hello!</div>

Related