suonpera suonpera - 11 days ago 5
HTML Question

change element based on time

I'm trying to change this element based on time: text

I found this snippet, but what do I change/add so that it effects the h1?

var myDate = new Date();

/* hour is before noon */
if ( myDate.getHours() < 12 ) {
document.write("Good Morning!");
}

/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) {
document.write("Good Afternoon!");
}

/* the hour is after 5pm, so it is between 6pm and midnight */
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {
document.write("Good Evening!");
}

/* the hour is not between 0 and 24, so something is wrong */
else {
document.write("I'm not sure what time it is!");
}


thanks in advance!

Joe Joe
Answer

Using JQuery:

var myDate = new Date();
var text = "";

/* hour is before noon */
if ( myDate.getHours() < 12 )  {
   text = "Good Morning!";
}

/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) {
   text = "Good Afternoon!";
}

/* the hour is after 5pm, so it is between 6pm and midnight */
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {
   text = "Good Evening!"; 
}

/* the hour is not between 0 and 24, so something is wrong */ 
else { 
   text = "I'm not sure what time it is!";
}

$("h1").text(text);

Without JQuery, the last line would instead be:

var h1s = document.getElementsByTagName('h1');
for(var i = 0; i < h1s.length; i ++) {
    h1s[i].innerHTML = text;
}
Comments