Blog

Previous Post: Pardon Our Dust »Happy Birthday Bryan! »Graphic Design Project: Memorial Cookbook Calendar »Now, for something REALLY good enough to eat. »Oh my god! Smells good enough to eat! »I've had a photo published! »So cool I had to share »Sara's Virtual Kitchen »Happy New Year »Help for the Last Minute Shopper »

3/07/2007

Time Sensitive CSS Switcher (Yes! You Can Change Styles Based on Time of Day!)

Sunrise
Sunrise
Morning
Morning
Noon
Noon
Afternoon
Afternoon
Sunset
Sunset
Twilight
Twilight
When I set out to redesign this site, I had an idea: Could I make the stylesheet change based on the hour of the day? Sounds easy enough, right? So, I started searching the Internet for some code I could use. I'm a novice when it comes to javascript and php, so I was hoping to find some "plug and play" code, so to speak.

I found code to switch styles based on day of the week, and month of the year, but not time of the day. The month/day code all used php, which used the SERVER time. So, it would switch styles based on the time stamp of the server where my website was hosted. But, since my styles were of the morning/noon/night variety, that wouldn't work. I was told I would have to use javascript, a client-side code, so it would work based on visitors' local time.

So, I began posting in various forums, hoping to find someone to help me. Still, no luck. I was beginning to think I would have to abandon the idea.

But I just couldn't let it go. I was like a dog with a bone. I kept searching...hoping that somehow I would find a buried treasure somewhere online. I was about to give up when I decided to ask one of my coworkers, a web programmer. I felt guilty asking for his help on a personal project, but I got over it!

Sure enough, in just a few minutes, he whipped out some code and told me to give it a try. And it worked! I was giddy. I awaited the turn of the hour, so I could see the magic in action. At 3 pm, I hit refresh, and voila. The stylesheet changed from my blue "noon" theme, to the blue/orange "afternoon" theme.

I have six different stylesheets. See the thumbnails at right.


  • From 5 am to 8 am, it displays the "sunrise" theme.
  • From 8 am to 12 pm, it displays the "morning" theme.
  • From 12 pm to 3 pm, it displays the "noon" theme.
  • From 3 pm to 6 pm, it displays the "afternoon" theme.
  • From 6 pm to 9 pm, it displays the "sunset" theme.
  • And finally, from 9 pm to 5 am, it displays the "twilight" theme.

Here's the code I used to make it happen:


<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function getCSS()
{
datetoday = new Date();
timenow=datetoday.getTime();
datetoday.setTime(timenow);
thehour = datetoday.getHours();

if (thehour > 20)
display = "tree_twilight.css";
else if (thehour > 17)
display = "tree_sunset.css";
else if (thehour > 14)
display = "tree_afternoon.css";
else if (thehour > 11)
display = "tree_noon.css";
else if (thehour > 7)
display = "tree_morning.css";
else if (thehour > 4)
display = "tree_sunrise.css";
else if (thehour > 1)
display = "tree_twilight.css";
else
display = "tree_sunset.css";

var css = '<'; css+='link rel="stylesheet" href=' + display + ' \/'; css+='>';

document.write(css);
// End -->
}
</script>
<script language="javascript">getCSS();</script>


You can select a default stylesheet, to account for folks with javascript disabled, by adding the following:


<noscript>
<link rel="stylesheet" href="tree_sunset.css" type="text/css">
</noscript>


Before I go, I must give credit to that coworker I was talking about. His name's Fidel. Check out his website at http://www.eriwebdesigns.com

Labels: , ,


 

75 Comments:

At 6:04 PM , Anonymous Anonymous said...

Nice concept

 
At 6:36 PM , Anonymous Anonymous said...

i wonder if there's a patch to handle daylight savings time ;-)

 
At 9:11 PM , Anonymous Anonymous said...

Great idea. Sadly it doesn't seem to be working for me. I'm looking at your site at 12:08am using Firefox on a windows machine and I'm seeing the 'afternoon' background.

I'm going to bookmark your page and try again at different times of the day to see if it changes.

 
At 5:28 AM , Anonymous Anonymous said...

No offense, but using document.write to simply write out the stylesheet link tag to the document is a pretty foul solution. A much better solution would be to ID your existing stylesheet link tag and simply modify the src for it. Even better would be to have a base stylesheet, then append an additional custom time of day stylesheet on top of (or rather, after) the base stylesheet, using appendChild.

 
At 5:32 AM , Anonymous Anonymous said...

Hey,

Nice work!

If you want to try it out, just change your computer clock and refresh! ;)

Ive just seen all the style sheets within a few mins..

Cheers for the code, may use it one day!

Thanks

fLUx

 
At 5:46 AM , Anonymous Anonymous said...

Cool, I had the same idea a few months ago and did pretty much the exact same thing here: AspectRadio.com (shameless plug)

except I only did 4 different time based layouts: morning,noon,evening,night.
P.S. be kind, we're in the process of moving servers and expanding our services
-XDrive05

 
At 5:49 AM , Anonymous Anonymous said...

Hi,

I tried a similar thing with my website but it wasn't to change the CSS it was just to change the background colour, the hope was to give the user a sense of the time of day by representing the time of day with the colour of the sky at that time. If you want to see the code, please see www.thursdaynightadventures.ca or email me and I will send you the Javascript I have around here somewhere.

Regards,

Tom (mezay@hotmail.com)

 
At 5:58 AM , Anonymous Anonymous said...

Great website. Similar to WorldClockr

Best Regards

Dan

 
At 6:16 AM , Blogger willemmulder said...

would be fun if the site would grab the time that would pass before a new 'theme-time' would start, and then would set a timer that would change the theme at that given time.
(that's a lot of would)
Not very usefull, but still fun for people watching the site just before 'theme-time-change'.

 
At 6:41 AM , Anonymous Anonymous said...

Got something working on my site:
www.misohoni.com/diary/

If all is well, I can forward you on the code.

 
At 6:55 AM , Anonymous Anonymous said...

Just for reference - here's an example of how you do this server side with PHP:

// Get 24-hour time:
$hour = date('H');

if ($hour < 8) {
$css = '#container {background: transparent url(bg_night.gif)}';
} elseif ($hour < 17) {
$css = '#container {background: transparent url(bg_day.gif)}';
} elseif ($hour < 21) {
$css = '#container {background: transparent url(bg_cloud.gif)}';
} else {
$css = '#container {background: transparent url(bg_day.gif)}';
}
echo 'OPENstyle typeEQUALS"text/css"CLOSE'.$css.'OPEN/styleCLOSE';

Replace OPEN with <
Replace EQUALS with =
and CLOSE with >

 
At 7:20 AM , Anonymous Anonymous said...

Alistair, she already found code like that for PHP. But like she said, it's server side, so you don't get the same effect.

Nice job...I'll be checking back later to see it change :)

 
At 7:37 AM , Anonymous Anonymous said...

For those who will be checking back to see if it changes, just change your damned system time!!

 
At 8:09 AM , Anonymous Anonymous said...

There is an error in the logic. Like one of the user's said he was getting the sunset theme at 12:08am or 0:08. Since you check to see if the hour is greater than 1 it does not apply the twilight theme. That last else if statement should be > 0. Or the first one should be ((thehour > 20) && (thehour < 5))

 
At 8:17 AM , Anonymous Anonymous said...

It's only cool because you have a tree in your header, but on other blogs without a relevant design that fits in with nature or atmosphere - it would be pointless. Also this relies on Javascript so it's not accessible, but still good job I guess.

It's low tech, and I wouldn't say you're the first to do this, but nice job anyways.

 
At 8:55 AM , Anonymous Anonymous said...

@ "For those who will be checking back to see if it changes, just change your damned system time!!"

What's the fun in that?

 
At 8:56 AM , Anonymous Anonymous said...

This is brilliant.

Is it continous though? You could have it repeating every 1 hour.

 
At 9:03 AM , Blogger Andrew said...

There is actually a much simpler solution which you might consider.
1) place all your different styles into one stylesheet and place a class on your "body" tag. This class represents what time of day it is. For instance if you had a rule like
#foo {background-color: red} in your morning stylesheets change it to
.morning #foo {background-color: red}
etc.
2) just include this new big stylesheet normally - without document.write.
3) in the javascript instead of document.writing the different stylesheets, just change the class on the body tag to match the time of day. The style rules set which match that class will automatically be applied. like document.body.className='morning'.

This has several benefits:
1) you can share common styles across the times like margins and padding - without having to maintain several stylesheets
2) the stylesheet will be cached for the folks coming the 2nd time and load faster.
3) less browser issues with changing a classname vs document.write.

 
At 9:11 AM , Anonymous Anonymous said...

For the record, you can do this server-side in PHP -- you just have to look beyond the simple date() function.

It requires a bit more research and work, but using an ip-to-country database and checking against that country's DST schedule will give you the same results, even when they've turned their scripting off... You can even make it (largely) insensitive to the use of proxy servers, and probably get better (or at least more wide-spread) accuracy than through the use of JS.

 
At 9:35 AM , Blogger bLiTzJoN said...

I would go with Andrew's className code so the page will render with a basic default css and the page code will be better formatted especially if you are staying validated to stay within strict doctypes or want parsers to render the page (for those that use wysiwyg editors, like Dreamweaver)

 
At 9:35 AM , Blogger Unknown said...

I really like the idea of "ambient information" coming through in the design of sites. I've been doing a time-of-day / weather-based CSS switcher for a few months now (http://www.nicholasjon.com/permalink/2007/1/14/time_sensitive). It's great! Nice work.

 
At 9:46 AM , Blogger Andrew said...

Next challenge: query a weather api somewhere and include clouds, rain, hail, or snow based on the weather :)

 
At 9:59 AM , Anonymous Anonymous said...

Amazing! I had this exact idea back in October when creating one of many sites. Even the tree was in the idea. I'm glad yet disappointed to see someone pull it off. Congrats on your hard work, it has paid off.

 
At 11:06 AM , Blogger Unknown said...

very sexy design

 
At 11:54 AM , Anonymous Anonymous said...

see http://devshots.com

 
At 12:06 PM , Anonymous Anonymous said...

SAME AS: http://www.dynamicdrive.com/dynamicindex9/stylesheetswitcher.htm

Actually, even better than.

And frankly, I trust DD more than some 13 year old script kiddie who comes up with this at 3 AM.

 
At 12:10 PM , Anonymous Anonymous said...

Thanks for this Katherine. I used it on my site here:

http://1000geeks.com/css/time_sensative/

 
At 1:10 PM , Anonymous Anonymous said...

hmmm will it correspond with your computers clock or one timezone?

 
At 1:32 PM , Anonymous Anonymous said...

That is rather cool.

 
At 1:45 PM , Blogger Jason said...

neat, although it'd be even cooler if it updated live, like if you were on the site during the hour change, it would change without having to refresh. you could add a timer to the page and have it just run every second.. ok, it's a bit overkill, but it would add to the coolness.

there's another site out there on the web that not only has the theme based on the time, but also the weather... i forget the name of it, but it's a neat site.

 
At 2:06 PM , Anonymous Anonymous said...

Hi. I just got done reading a DOM scripting book, so I was inspired to try it out with some of the things I just learned.

This is based on having a link tag already established in the HTML.

function timeCSS() {
var sheet = document.getElementsByTagName('link')[0];
var sheetFile = sheet.getAttribute('href');
alert('The css file is: ' + sheetFile);
var dateToday = new Date();
var timenow = dateToday.getTime();
dateToday.setTime(timenow);
var thehour = dateToday.getHours();
if (thehour > 12) {
sheet.setAttribute('href','styles/after12.css');
}
else if (thehour < 12) {
sheet.setAttribute('href','styles/before12.css');
}
}


You can then use your favorite onLoad method to call the script. This could probably be reworked slightly to create a new link element node with a smaller stylesheet calling only the differences from a base sheet. That way, you wouldn't need to have multiple full stylesheets.

 
At 2:15 PM , Blogger kulpreetsingh said...

This is very cool. :)

I have a question - does it display the appropriate CSS according to the user's computer time or your time?

 
At 2:56 PM , Blogger Scatropolis said...

Awesome! I guess the next step would be to dynamically create the gradients and have it change everyminute. I'd spend more time on your site then google if that was the case :)

I'm thinking about making this as a kind of wallpaper that maybe changes depending on time. We'll see.

 
At 2:59 PM , Blogger Efwis said...

kulpreet,
Since this uses javascript it will use the users computer time.

javascript code uses commands to pull the information from the browser.

 
At 3:39 PM , Blogger Douglas Gottlieb said...

Very nice. Great idea & design

 
At 3:47 PM , Blogger will said...

This comment has been removed by the author.

 
At 3:54 PM , Blogger will said...

Interesting enough. Now what you should do is:

Get IP Address of the visitor, locate its procendence (e.g. mine: Lux, EU.)

Get timezone in the region (e.g. mine: gmt+1)

Set css accordingly.

Share the script under Creative Commons. ;)

Cheers!

/Will. (digg: williamm)

p.s. this idea is because the js isn't working on Safari, and your site has the afternoon css whie its nearly 1am.

 
At 6:09 PM , Anonymous Anonymous said...

Here is a version of the same page that avoids 'document.write()' and switches between alternate stylesheets on the fly:

http://www.wingo.com/katgal/

and a demo where one second == one hour:

http://www.wingo.com/katgal/

 
At 6:11 PM , Anonymous Anonymous said...

Here is a version of the same page that avoids 'document.write()' and switches between alternate stylesheets on the fly:

http://www.wingo.com/katgal/

and a demo where one second == one hour:

http://www.wingo.com/katgal/index_demo.html

 
At 6:37 PM , Blogger Unknown said...

Is there anyway this can be applied to a Goggle Blogger page? Does anyone know? Email me if you have any thoughts.

 
At 6:57 PM , Anonymous Anonymous said...

i reckon you could choose some better colour schemes seeing as sunset blends the purple and yellow into a fudgy brown but other than that very cool

 
At 7:34 PM , Anonymous Anonymous said...

By the way, none of the links on your sidebar work.

 
At 7:35 PM , Blogger Hal said...

In response to Andrew, all of the sites for tv stations owned by CBS change the logo based on the current weather (for example, wcbstv.com). The complete list of sites is at cbslocal.com (just the CBS sites, though).

 
At 9:29 PM , Blogger ken215 said...

As an anonymous said above, there is a bit of a logic error in the code. I tried it out at various times, and found that between 00:00:01 (just after midnight) and 01:59:59 it displays the sunset theme instead of twilight. A simple fix would be to change this code:

else if (thehour > 1)
display = "tree_twilight.css";
else
display = "tree_sunset.css";

to this:

else
display = "tree_twilight.css";

 
At 7:54 PM , Anonymous Anonymous said...

Wow , it's amazing. I like this concept.

 
At 3:40 PM , Anonymous Anonymous said...

Inspired. Thanks.

 
At 1:43 PM , Blogger -_- said...

wonderful !!

 
At 1:53 AM , Anonymous Anonymous said...

wow! great, until now my site http://designersyard.com is not good as that.

 
At 12:53 AM , Anonymous Anonymous said...

oh my god! I've actually thought about a code like this for years! well, a few years ago I was wondering if there was a code where the layout could switch depending on the time of the day, my plan was to display what "I'm doing right now" like sleeping at night, at school during the day, etc. I love this code, and I'm probably going to use it someday :)

 
At 5:33 AM , Anonymous Anonymous said...

very cool.

a few notes though, to make this XHTML strict...

instead of: LANGUAGE="JavaScript"
use: type="text/javascript"

And:
var css = '<'; css+='link rel="stylesheet" href=' + display + ' \/'; css+='>';
Change to:
var css = '<'; css+='link rel="stylesheet" href="' + display + '.css" \/'; css+=' />';

lastly, instead of the whole noscript stuff, place the default style sheet just above the script. the javascripts stylesheet call will overwrite the fallback script.
(http://www.ensellitis.com for example of how i did it, sorry for the sucky graphics, i will be changing when i have more time)

thanks for this, i suck at java, and didnt want to do this via PHP

 
At 6:36 PM , Anonymous Anonymous said...

This is amazing cat, it inspires me with a new idea for my next IPB Skin, thanks a million ;)

 
At 6:44 AM , Anonymous Anonymous said...

Hey this is wonderful. What you think could the page < title > be changed with similar code as well? I tried but didn't have any luck...many thanks

 
At 1:40 AM , Anonymous Anonymous said...

Amazing!

 
At 2:10 PM , Anonymous Anonymous said...

Brilliant.

Very clever idea, IE is such a pain when us developers try and create a new idea!

 
At 6:54 AM , Anonymous Anonymous said...

Wonderful idea!

 
At 8:46 AM , Blogger Katherine said...

Jaie,

Sorry! I accidentally deleted your comment while getting rid of all the recent spam posts. I'll paste it below.

"Mu university's student site has just done this same thing.

out of curiosity it could have been done on the server side, avoiding any javascipt, and document.write() problems.

And looking a the png problem in ie6, you may be able to solve the problems by using transparent gifs."

The PNG issue is solved, btw. Used iepngfix.

As I'm sure you know, gifs really only work if you have a totally solid background. Their "transparency" isn't quite up to snuff.

 
At 3:32 PM , Anonymous Anonymous said...

Hmm, its a great idea, nice one.

 
At 7:14 AM , Blogger Unknown said...

This is a very good script, the best one i ever seen and i wanna use it on my wordpress blog. Can you tell me how to "set up" this script? Thanks

 
At 3:36 AM , Blogger Gowri said...

This comment has been removed by a blog administrator.

 
At 10:09 AM , Anonymous Anonymous said...

www.taprootcreative.com has a similar effect that has inspired me to do it on my next project, but I hadn't yet gotten to the coding of that yet. Thank you so much for posting, and to StumbleUpon to finding this post for me.

 
At 4:37 AM , Anonymous Anonymous said...

I was looking for the same thing... Very nice.
One question can you post how your css looks like, because i have some trouble making the image go on the hole screen.
10x

Ivo

 
At 8:44 AM , Anonymous Anonymous said...

One more thing, i want to change only one image, and i'm tryed to put it as java call function but it doesnt work. I want to chane just the image file according to the time, but not the background

reguards Ivo

 
At 9:10 AM , Blogger Katherine said...

Ivo, Do you have a link to your site so I can see what you're talking about? If the image itself isn't the width of the full screen (or formatted to tile seamlessly), you really can't force it to expand to the width of the screen with css.

With regards to your second question, just create a div with the exact dimensions of the image and set the style of that div to have the image as its background. Then you can switch it with the styleswitcher.

If you use firefox with the webdeveloper plugin, you can right click on the page and view the css on any page. It's very helpful!

Feel free to contact me directly (use contact link above), if you have any more questions.

 
At 10:21 AM , Anonymous Anonymous said...

Sorry didnt find your e-mail.
here is the site i just put up:
http://prazen.free.bg/test/home.html

i want to change that picture with the grass and the glass, and (maybe) the hole theme of the site.

Thank you in advance
Reguards Ivo

 
At 11:44 AM , Blogger Katherine said...

You need to make a style class and apply it to the table cell that's currently holding that image. And instead of inserting the image in the table cell, you use the background-image tag in the css.

 
At 12:38 PM , Blogger Mr. Apache said...

Cool idea! I wish you were using unobtrusive javascript but its nice! I much prefer using Apache .htaccess to do this same thing, no javascript, no programming, so easy. CSS Time Switcher using .htaccess

 
At 12:42 PM , Anonymous Anonymous said...

Unfortunately your page has 485 errors - ouch and ouch again!!!
http://validator.w3.org/check?uri=http%3A%2F%2Fwww.katgal.com%2F2007%2F03%2Ftime-sensitive-css-switcher-change.html&charset=%28detect+automatically%29&doctype=Inline&group=0

 
At 12:52 PM , Blogger Katherine said...

Can't take the blame for the vast majority of those. I use blogger and most of those validation errors are caused by their code.

 
At 7:06 AM , Anonymous Anonymous said...

really smart idea ! i like it

 
At 9:49 PM , Anonymous Anonymous said...

Does it still work in Firefox and IE?

 
At 6:28 AM , Anonymous Anonymous said...

Excellent idea!

i think i could have a use for the code!

cheers

again nice!

 
At 8:01 AM , Anonymous Anonymous said...

site with the same idea:
www.okc.ru

 
At 12:03 AM , Blogger Monzstro said...

This comment has been removed by the author.

 
At 12:05 AM , Blogger Monzstro said...

is their a copyright issue with using your code?

 
At 4:16 AM , Blogger sssss said...

Hi,
pls forgive me for this stupid post.Im a beginer.
Could let me know how's looking a css file (for example tree_twilight.css)?Have a link where download all files? Thank you.

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home