Div appear only once

Asked

Viewed 263 times

2

How to make a Div (not a pop-up, but more like a protective screen) appear once every 6 hours using Jquery and Cookies? I can’t use PHP because the platform I’m using is Blogger and it doesn’t allow.

1 answer

0


You can use localStorage, that has behavior similar to the cookie

The code below will create a localStorage with the value in milliseconds of the current time + 6 hours forward. At each page load, the code will subtract the time stored in the localStorage the value in milliseconds of the current time; if the result is negative, it means that the 6 hours have passed since the creation of the localStorage and will show the div, and at the same time renew the localStorage with another 6 hours ahead.

This would be an example of div, which must initially have display: none;:

<div id="tela" style="display: none; width: 200px; height: 200px; background: red;">
   Só irá aparecer novamente após 6 horas
</div>

This is the code:

function criaCookie(){
   var data_at = new Date();
   var data_6h = new Date(data_at);

   var data_6h = data_6h.setHours(data_at.getHours()+6);

   localStorage.protetor = data_6h;
}

$(document).ready(function(){ 
   if(localStorage.getItem("protetor") === null){

      criaCookie();
      $('#tela').show();

   }else{

      var tempo_fim = localStorage.protetor;

      var data_at = new Date();
      var data_at = data_at.setHours(data_at.getHours());
      var tempo = tempo_fim - data_at;

      if(tempo <= 0){
         localStorage.removeItem("protetor");
         criaCookie();
         $('#tela').show();
      }

   }

});

Functional 1 minute sample for testing

For test purposes, this example shows that the div will only appear every 1 minute. Execute the code and run again after a few seconds. On the first run, the div will be displayed, at the second run, no more. Wait 1 minute and run again, and the div will be shown.

Testing in the Jsfiddle

  • huahuahua, functional example!!!!

  • @Leocaracciolo ahah... I will patent: exemplo funcional©. rsrsrs

  • I’ll have to pay royalties??

  • @Leocaracciolo of course not, I provide you a 30 day leave for evaluation rs

  • hahahahaha, I’ll think about it

  • Man I find very interesting your example, congratulations but I also managed to implement a button, confirmation in case the user wants to close the Div being aware of it, in case what I did was like this, I removed the creatiCookie(); and inserted inside a new function, inside that function it gives the None display in the div and returns to the createCookie(); and of course, the button is inside the div

  • @Joãovictor It’s cool also the way you did. If you found the answer useful, be sure to mark it . Abs!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.