Div appear once

2

How to make a Div (not a pop-up, but more like a screen saver) pop up only once every 6 hours using JQuery and Cookies? I can not use PHP because the platform I'm using is Blogger and it does not allow it.

    
asked by anonymous 09.12.2017 / 17:26

1 answer

1

You can use localStorage , which behaves similarly to cookie

The code below will create a localStorage with the value in milliseconds of the current time + 6 hours ahead. At each page load, the code subtracts the time stored in localStorage by 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 localStorage and will show div , and at the same time renew localStorage with 6 more hours ahead.

This would be an example of div , which should 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 example of 1 minute to test

At the end of the test, this example shows that div will only appear every 1 minute. Run the code and run again after a few seconds. On first run, the div will be displayed, in the second run, no more. Wait 1 minute and run again, and div will be displayed.

JSFiddle Test

    
09.12.2017 / 18:42