Reputation: 23
Depending on the time of the day. I am trying to display Morning, Afternoon or Evening to the user using the JavaScript ( new Date() ) method. But what I am receiving in response is just the (else) statement. Can I get advice as to what I am doing incorrectly?
const mainHeader = document.getElementById("header");
var greetings = () => {
var today = new Date();
}
window.onload= (e) => {
greetings;
if(today >= 1 && today < 12) {
mainHeader.innerHTML = "<h3>Good Morning! And Welcome To Guess The Number</h3>"
console.log("Morning: between 1 and 12");
} else if(today >= 12 && today < 17) {
mainHeader.innerHTML = "<h3>Good Afternoon! And Welcome To Guess The Number</h3>"
console.log("Afternoon: between 12 and 17");
} else if(today >= 17 && today <= 24) {
mainHeader.innerHTML = "<h3>Good Evening! And Welcome To Guess The Number</h3>"
console.log("Evening: between 17 and 24");
} else {
mainHeader.innerHTML = "<h3>Welcome to Guess The Number</h3>"
console.log("No time zone");
}
}
Upvotes: 0
Views: 39
Reputation: 780974
You need to return the hour from greetings()
, and then assign it to a variable in the window.onload
function.
const mainHeader = document.getElementById("header");
var greetings = () => {
var today = new Date();
return today.getHours();
}
window.onload = (e) => {
var today = greetings()
if (today >= 1 && today < 12) {
mainHeader.innerHTML = "<h3>Good Morning! And Welcome To Guess The Number</h3>"
console.log("Morning: between 1 and 12");
} else if (today >= 12 && today < 17) {
mainHeader.innerHTML = "<h3>Good Afternoon! And Welcome To Guess The Number</h3>"
console.log("Afternoon: between 12 and 17");
} else if (today >= 17 && today <= 24) {
mainHeader.innerHTML = "<h3>Good Evening! And Welcome To Guess The Number</h3>"
console.log("Evening: between 17 and 24");
} else {
mainHeader.innerHTML = "<h3>Welcome to Guess The Number</h3>"
console.log("No time zone");
}
}
<div id="header">
</div>
Upvotes: 1
Reputation: 5387
You never define today
in the onload function(even if you called greeting, today wouldn't be defined b/c var is function scoped). Instead replace greetings;
with var today = new Date().getHours();
and remove the greetings function.
If you still want to keep greetings
as a function, you can replace it with var greetings = ()=>new Date().getHours();
and replace greetings;
with var today= greeting();
Upvotes: 0