Search code examples
javascripthtmlvarprompt

I need a prompt to show just once, save a username, and use it in the rest of the site


First post. I am really new at Javascript, so I may be asking a lot around here. Well, the problem is this: The user enters the site, a prompt asks for their name and then, the DOM is edited to show a 'h3' saying "Welcome userX". But, the first problem was that, since the .js file was shared by every file of the site, it showed the prompt every time. To avoid this, I added the code in a function that is called when the body is loaded.

var salute = function(){
    var user = prompt("Por favor ingrese su nombre", "Usuario");
        if( user==null){
        user = "Usuari@ sin nombre"
    };

    var saludo = document.getElementById("saludo");

    saludo.innerHTML= "Bienvenido " + user; 

}

But, since I have this: <body onload="salute();"> Whenever the user goes back to the "Home" they are asked for its name again. How can I do to avoid this? And aslo, is there a way to use the "user" variable in another part of the site? For example, in an image gallery, make it to say "We hope you enjoy this pictures, user"


Solution

  • If you want to persist (localstorage) the username for next visits, and across other pages, then you may use this, and enhance it with additional validations:

    var salute = function() {
      var user = localStorage.getItem("user");
    
      if (!user) {
        user = prompt("Por favor ingrese su nombre", "Usuario");
        if (user) {
          user = localStorage.setItem("user", user);
        } else {
          user = "Usuari@ sin nombre"; //Your default one
        }
      }
    
      var saludo = document.getElementById("saludo");
      saludo.innerHTML = "Bienvenido " + user;
    
    }
    

    Hope it works!