Reputation: 225
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!
Upvotes: 0
Views: 1006
Reputation: 2540
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;
}
Upvotes: 0
Reputation: 2642
You need to have one h1 tag on your page, and you can give 'id' attribute and change the contents according to the current time: Below code may help you
var myDate = new Date(); /* hour is before noon */ if (
myDate.getHours() < 12 ) {
document.getElementById('greeting').innerHTML ="Good Morning!"; }
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{ document.getElementById('greeting').innerHTML ="Good Afternoon!"; }
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{ document.getElementById('greeting').innerHTML= "Good Evening!"; }
else
{ document.getElementById('greeting').innerHTML="I'm not sure what time it is!"; }
<h1 id="greeting"></h1>
Upvotes: 1
Reputation: 335
You can change the document.write(...)
to document.getElementsByTagName('h1')[0].write(...)
This would write to the first h1
tag in your webpage
Upvotes: 0