Good morning.
Please, i want to show a salute-message depending on hours.. Tried this auto-initializing function, it works, but independs what time is it, he display: "Good Night". What i'm doing wrong?? Can anyone help?
Here is the code:
(function(){
function saluteText() {
var d = new Date();
var time = d.getHours();
var divInnerHTML = document.querySelector('.name');
if (time < 12) {
function addInnerHTML() {
divInnerHTML.innerHTML = 'Good morning!';
}
}
else if (time >=12 && time <18) {
function addInnerHTML() {
divInnerHTML.innerHTML = 'Good evening!';
}
}
else if (time >= 18 && time < 24) {
function addInnerHTML() {
divInnerHTML.innerHTML = 'Good night!';
}
}
addInnerHTML();
}
saluteText()
})();
I think that this is a problem of defining your functions.
When you define a function in javascript, it is placed on top of the scope.
You define the function three times and the last one is only shown. Even if you place the declaration between If statements all three will be created.
You can try this out by removing the last function and you will see that the code says 'Good evening'.
In this case the solution to your problem would be this approach: