Show a div only when you enter the page the first time

2

I have a div with a message, I want it to be shown only when a visitor enters the page for the first time, if it enters a second time it is not shown. I have this code that I found but it does not work

var mensaje = document.cookie.split('mensaje=')[1]; // obtenemos la cookie "mensaje"
if(mensaje != null) // si la cookie está definida
    document.getElementById('mensaje').style.display = 'none';  // ocultamos el div#mensaje
else // si no está definida la cookie
    document.cookie = 'mensaje=visto;path=/'; // la agregamos
#mensaje {
padding:20px;text-align:center;font-family:sans-serif;background-color:#FFD7D7;
}
<div id="mensaje">
    Prueba. Entraste por primera vez 
</div>
    
asked by Daniel 07.06.2017 в 02:20
source

2 answers

2
<div id="mensaje" style="display:none;">
   Prueba. Entraste por primera vez 
 </div>

Use the localStorage in the following way.

// verifica que el localStorage sea null para mostrar el mensaje
if( !localStorage.getItem('ingreso') ){

    document.getElementById('mensaje').style.display= 'block';
    // estableces el localstorage en 1 para que no se vuelva a cumplir la condicion
    localStorage.setItem('ingreso',1); 

} else {
    document.getElementById('mensaje').style.display= 'none';
}

Only use the code in the way that best suits you and so you can have the

    
answered by 07.06.2017 / 03:18
source
0

You can use this code only lasts the same as the session using kookie.

$(document).ready(function() {
  jQuery(function() {
    var getCookie = function(cname) {
        var name = cname + "=",
          ca = document.cookie.split(/;\s*/g);
        for (var i = 0; ca.length > i; i++) {
          var c = ca[i];
          while (c.charAt(0) == " ") c = c.substring(1);
          if (c.indexOf(name) == '0') return c.substring(name.length, c.length);
        }
        return "";
      },
      curr = new Date().toLocaleDateString(),
      last = getCookie("mensaje1");
    if (last != curr) {
      setTimeout(function() {
        document.cookie = "mensaje1=" + curr;
        last = curr;
      }, 300);
      $('#mensaje').show();
    } else {
      $('#mensaje').hide();
    };
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mensaje">
  Prueba. Entraste por primera vez
</div>
    
answered by 07.06.2017 в 12:59