Showing the Prompt on loading and store the value to greet the User every time he opens the HomePage

179 views Asked by At

I'm trying to ask the Users "What's your name" using a prompt message to get its name. Then, greeting the user with a welcome message based on the current time. So far, I could show the message only by clicking a button. What I wanted to do is asking first for the name and, once got the Username, show the message directly when the HomePage is loaded.

This is the HTML:

 <form> 
    <input id="show_button" class="button" type="button"   value="Hey! Click Me! I know you!" onclick="greet(), salutoTempo()" /> 
</form>

And this is the JavaScript Code:

var today = new Date();
var hourNow = today.getHours();   
var saluto;

   
if (hourNow > 17) {   
  saluto = "Good evening"
} else if (hourNow > 11) {
  saluto = "Good afternoon"
} else if (hourNow > 0) {
  saluto = "Good morning"
} else {
  saluto = "Welcome to Wolf the Barber!"
}

var el = document.getElementById("greeting");





function salutoTempo(){
   document.getElementById("greeting").innerHTML = saluto + " ";
}




function greet(){
   name = localStorage.getItem("name");
   if (name == null || name == "null"){
     alert("Hi, Stranger!");
     name = prompt("What is your name?");
     localStorage.setItem("name", name);
     var greeting = document.getElementById("greeting").innerHTML = (greeting);
     var Username = document.getElementById("greeting1").innerHTML = (name + "!");
 } else {
     var greeting = document.getElementById("greeting").innerHTML = (greeting);
     var Username = document.getElementById("greeting1").innerHTML = (name + "!");
   } // end greet
 } // end function

Thanks guys!

1

There are 1 answers

0
Ele On

According to your question, you can use onloadattribute in body tag. Additionally, call the function salutoTempo.

<html>
<body onLoad = "greet()">
 <form> 
    <input id="show_button" class="button" type="button"   value="Hey! Click Me! I know you!" onclick="greet(), salutoTempo()" /> 
</form>

<span id="greeting"></span>
<br>
<span id="greeting1"></span>

<script>
var today = new Date();
var hourNow = today.getHours();   
var saluto;

if (hourNow > 17) {   
  saluto = "Good evening"
} else if (hourNow > 11) {
  saluto = "Good afternoon"
} else if (hourNow > 0) {
  saluto = "Good morning"
} else {
  saluto = "Welcome to Wolf the Barber!"
}

var el = document.getElementById("greeting");

function salutoTempo(){
    document.getElementById("greeting").innerHTML = saluto + " ";
}


function greet(){
   name = localStorage.getItem("name");

   if (name === null || name === "null"){
     alert("Hi, Stranger!");
     name = prompt("What is your name?");
     localStorage.setItem("name", name);     
     document.getElementById("greeting1").innerHTML = (name + "!");
   } else {
     document.getElementById("greeting1").innerHTML = (name + "!");
   } // end greet
   salutoTempo();
} // end function
</script>
</body>
</html>