Can use Localstorage (LS), which is also a cookie. All you need to do is store primitive value of the current date and create another date by adding +24 hours to the current date and then making the comparison. If LS does not exist shows the popup and sets its value +24 hours. If it exists, make the comparison, if it is smaller show the popup and reset the time.
Whereas your popup id is #popup
, guy:
<div id="popup">
CONTEÚDO DA POPUP
</div>
Hide the popup div in CSS:
#popup{ display: none }
And that would be the whole function:
document.addEventListener("DOMContentLoaded", function(){
// pega o elemento da popup
var popup = document.getElementById("popup");
// atribui o LS a uma vaviável
var ls = localStorage.getItem("popup");
// pega a data atual
var data = new Date();
// variável para guardar a data atual
var data_atual = data.valueOf();
// adiciona 24 horas à data atual
var data24 = data.setHours(data.getHours()+24);
// verifica se o LS é menor do que a data atual
// ou se o LS for inexistente
if(ls < data_atual){
// mostra a popup
popup.style.display = "block";
// cria/redefine o LS com o nome "popup" com a data +24 horas
localStorage.setItem("popup", data24);
}
});
Test of 5 seconds:
As here in the sandbox the LS does not work, change the line:
var data24 = data.setHours(data.getHours()+24);
To
var data24 = data.setSeconds(data.getSeconds()+5);
Re-load your page within 5 seconds and you will see that the popup will not appear. After 5 seconds it will appear 1 time, and so on.
I’ll leave down the dry code without comment:
document.addEventListener("DOMContentLoaded", function(){
var popup = document.getElementById("popup");
var ls = localStorage.getItem("popup");
var data = new Date();
var data_atual = data.valueOf();
var data24 = data.setHours(data.getHours()+24);
if(ls < data_atual){
popup.style.display = "block";
localStorage.setItem("popup", data24);
}
});
it wasn’t, the code didn’t work.
– Vitor Giovanny
The createCookie function only admits two parameters. You are calling it with three. From what I understand, the correct function statement would be
function createCookie(name,value, expireDays)
And on the date.setTime line do:date.setTime(date.getTime()+(expireDays*3600*24));
. It is even good practice to doconst MILLISECONDS_IN_A_DAY = 86400000
and reuse this constant instead of using the "hardcode" option to make3600*24
, typing the value directly. Following this recommendation, we would have:date.setTime(date.getTime()+(expireDays*MILLISECONDS_IN_A_DAY));
– João Pedro Henrique
I have implemented in my previous response another solution, if I may try! :)
– Rapha Leão