Put only 1x popup every 24h per user

Asked

Viewed 199 times

2

I’m trying to manipulate cookies here with javascript, I’m trying to put, that only displays popups once every 24 hours per user, but it’s showing up every time I enter the page.

Here my code, where am I missing? My logic is wrong ?

function checkLoading(e){
    d = new Date();
    document. cookie = "visto= true; expires = " + d.toUTCString() + ";path=/";
    d.setDate(d.getDate() + 1*24*60*60);

    if ( popupFormSubmitting == true ) {
        if(document.cookie == null){
            signupFormLoader.style.display = 'block'; 

        }
    }else{

        signupFormLoader.style.display = 'none'; 
    }
}

2 answers

3

It’s not entirely wrong your way of handling, but you’d better do it in a simpler way like this:

if (document.cookie.indexOf("popupShown=true") == -1) {
    document.cookie = "popupShown=true; max-age=86400"; //86400: segundos em um dia
    // Faça o restante logo aqui abaixo
}

So, after the cookie wins (After this 24H), the next time the page loads the popup will appear! See it carefully in the documentation of the cookie to ask too many questions or leave the comment here if there are more questions about it! :)


Since the previous code didn’t work with you, let’s try something different... Second this response in Stack, you must do this way so that you can actually set/read your cookie by Javascript and adapting to what you want:

function createCookie(name,value) {
    var date = new Date();
    date.setTime(date.getTime()+(3600*24));
    var expires = "; expires="+date.toGMTString();
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

And once you’ve done that, you just add this:

jQuery(document).ready(function() {
    var visto = readCookie('visto');
    if (!visto || visto !== "true") {
        createCookie('visto', "true");
        // Código do popup e demais códigos aqui
    }
});

Let’s see if it works now! Haha

  • it wasn’t, the code didn’t work.

  • 1

    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 do const MILLISECONDS_IN_A_DAY = 86400000 and reuse this constant instead of using the "hardcode" option to make 3600*24, typing the value directly. Following this recommendation, we would have: date.setTime(date.getTime()+(expireDays*MILLISECONDS_IN_A_DAY));

  • I have implemented in my previous response another solution, if I may try! :)

1

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);
   }
});

Browser other questions tagged

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