0

I want to set a DOM objects css display property to 'block' for 2 seconds and then have it set back to 'none' after the 2 seconds. How can this be done in just javascript? I am really new to this so don't really get jquery just yet.

I tried

document.querySelector(".one-rolled-popup").style.display = "block";

and then set it to

document.querySelector(".one-rolled-popup").style.display = "none";

after some other operations but this just hides it completely

Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
PumpkinBreath
  • 831
  • 1
  • 9
  • 22

3 Answers3

2

use setTimeout. It will execute a method after X milliseconds. Such in your case, you will display the block & then set it back to no-display after 2 seconds.

method () {
  // display it
  document.querySelector(".one-rolled-popup").style.display = "block";

  // hide it after 2 seconds
  setTimeout(() => {
      document.querySelector(".one-rolled-popup").style.display = "none",
  2000);
}
Danyal Imran
  • 2,515
  • 13
  • 21
1

You can do the following using setTimeout. I suppose that by default the div is visible so I don't have to show it.

setTimeout(
  function() {
    document.querySelector(".one-rolled-popup").style.display = "none";
  }, 2000);
<div class="one-rolled-popup">Testing</div>

But if it's hidden by default you could do this instead (click on the screen in the snippet to see the effect) :

function showAndHide() {
  document.querySelector(".one-rolled-popup").style.display = "block";
  setTimeout(
    function() {
      document.querySelector(".one-rolled-popup").style.display = "none";
    }, 2000);
}



window.onclick = function() {
  showAndHide();
}
.one-rolled-popup {
  display: none;
}
<div class="one-rolled-popup">Testing</div>
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
1

Try this function

   setTimeout(function(){ 
   if (document.querySelector(".one-rolled-popup").style.display == "block";) {
      document.querySelector(".one-rolled-popup").style.display= "none";
   } else {
      document.querySelector(".one-rolled-popup").style.display= "none";
   }

  }, 3000);
Sanjit Bhardwaj
  • 893
  • 7
  • 13