Smocks MCM
Smocks MCM

Reputation: 35

Displaying morning, afternoon, or evening to user based on time using variables

I want to say "Good morning, User" (morning can be changed to afternoon or evening) my code is not working. I'd appreciate any assistance.

index.html snippet

 <h1 class="mx-3 text-center display-3">Good <span id="time"></span>, Username</h1>

master.js

var today = new Date()
var curHr = today.getHours()
var time = null;

if (curHr < 12) {
  var time = "Morning";
} else if (curHr < 18) {
  var time = "Afternoon";
} else {
  var time = "Evening";
}

document.getElementById("time").innerHTML = time;

Sorry, I'm a noob at javascript.

I'd also like to know what this error means (from google chrome console):

Uncaught TypeError: Cannot set property 'innerHTML' of null
    at master.js:13

Upvotes: 2

Views: 3423

Answers (1)

pepperjack
pepperjack

Reputation: 663

If you are linking the javascript file before the span, then Uncaught TypeError: Cannot set property 'innerHTML' of null at master.js:13 will occur since it can't find the span yet. Try:

window.onload = function(e){ 
    document.getElementById("time").innerHTML = time;
}

Upvotes: 2

Related Questions