How to Display Dymanicly Timed Content using Javascript
Posted on Dec.12, 2009No Comments How To, JavascriptI’ve spent many a long hour playing with this javascript to make it work seamlessly. You can see the results, daily, on my website.
If you want to change your website background depending on the time of day you will need this specific code. Otherwise, make sure to read till the bottom so you understand and don’t come back to me asking why it isn’t working for you.
|
Nighttime on ThatGuyCharlie
|
Daytime on ThatGuyCharlie
|
Copy this text into your webpage before the tag.
Ok now, if you didnt understand that, here’s what’s happening.
now = new Date
Here we obtain the date from the user’s computer
if (now.getHours() < 4) {
document.write(“
“)
}
This bit of code says that if the hour of the day is before four o’clock AM, then print the css background style for night-time.
else if (now.getHours() < 10) {
document.write(“
“)
}
Again, this does the same, but checks to see if it is before 10 o’clock.
else if (now.getHours() < 24)
Remember to have this last part of your code so the script knows what to do up till midnight. The first code which defines “< 4" will only display the specified content from zero o'clock until 4 o'clock so to display content till midnight, you must have "< 24".
You can use this code and copy in different content to display at any time of the day by changing the hours. If you didn’t understand any of that, don’t worry! Test out the code at the top on your web-page and see if you can make it work. If not, comment below and I will try to help you out.
If you want to display symbols like apostrophes ” and backward slashes \ make sure to put a “\” before each one so that java-script recognizes it and dosen’t mess up your code.
Example of the WRONG way:
document.write(“hi! my friend said “I am going to the store ““);
Example of the RIGHT way:
document.write(“hi! my friend said \”I am going to the store\”“);
![[image: socialicon]](http://www.thatguycharlie.com/wp-content/themes/allthatstuff/img/social/twitter_16.png)
![[image: socialicon]](http://www.thatguycharlie.com/wp-content/themes/allthatstuff/img/social/flickr_16.png)
![[image: socialicon]](http://www.thatguycharlie.com/wp-content/themes/allthatstuff/img/social/facebook_16.png)
![[image: socialicon]](http://www.thatguycharlie.com/wp-content/themes/allthatstuff/img/social/youtube_16.png)
![[image: socialicon]](http://www.thatguycharlie.com/wp-content/themes/allthatstuff/img/social/deviantart_16.png)
![[image: socialicon]](http://www.thatguycharlie.com/wp-content/themes/allthatstuff/img/rss_sub.png)
![ThatGuyCharlie night-time background [image: TGCNight]](http://www.thatguycharlie.com/wp-content/themes/scyhigh/img/night.png)
![ThatGuyCharlie Day-time Background [image: TGCDay]](http://www.thatguycharlie.com/wp-content/themes/scyhigh/img/dayclouds.png)

