The innerHTML isn’t working in this JavaScript code.
var date = new Date();
var time = date.getHours();
var morning = document.p.getElementById("greeting").innerHTML="Good Morning ";
var afternoon = document.write = "Good Afternoon ";
var evening = document.write = "Good evening";
if (time < 12){
morning}
else if (time < 18){
afternoon}
else {evening};
The HTML code is
<p id="greeting"> </p>
I am trying to get the code to read “good morning” or “afternoon”, based on the time. The JavaScript is in an external file. It worked with document.write but in the external file, the greeting appears at the top of the page.
Here I am trying to set a
of ‘greeting’ based on time of day.
What this does is to introduce a variable called
afternoonand to set both it and the propertywriteondocument, which was previously a function call, to the string"Good afternoon".At a later point in your code, you just write
afternoon, which accesses the variable, but doesn’t do anything with it.It looks like you want to do something like this:
That is, the above would be the closest thing to your code, that is somewhat correct. I would still say that there is room for some improvement. Something like the following would make more sense to me:
Better yet, you could probably decide which message you want to use first, and then assign it, which would give you fewer places to change your code if you want to change where to output the greeting, for instance: