Main Menu


 

  
  

Recent Posts


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

Note: I know the layout breaks in ie 6. I'm working on it! But the style switcher still works!

Update (3/9/07): I've fixed the png issue for ie 6, but ie 6 doesn't appear to like my sIFR (flash) headlines. I'll be away for the weekend, so I'll take that issue up when I get back into town on Monday. Again, these are just layout issues. Not affecting the styleswitcher code below.


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 stysheets. See the thumbails 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: , ,

posted by Katherine at 9:10 PM  

43Comments:
Sharky said...

Great Design, unfortunately Microsoft's IE (V.6) blows all PNG based backgrounds and push your text thousands of pixels below...

10:25 AM

 
Katherine said...

Yeah, I know about the png issue, and I have a fix. Just haven't gotten that far yet. I was so darn excited about the styleswitcher, that I had to share right away.

As for the text appearing way down the page, hmmm. I'll have to look into that. I had tried out the page at browsershots.org. Perhaps I tweaked something that threw it all out of whack. Another mystery to solve.

10:56 AM

 
Katherine said...

Preliminary research seems to indicate that the second issue is related to the flash (sIFR) headlines. Only happens in flash-enabled IE 6. I'll have to write up an exception for that...

11:12 AM

 
Katherine said...

Ok folks, I've temporarily staunched the ie 6.0 bleeding. By no means fixed, but at least it's not displaying those god awful non-transparent pngs. I won't be able to spend much time on the site over the next few days, so all you ie 6 users will just have to deal. (Firefox is much better, anyway! Click here to download Firefox if you don't already have it.

5:01 PM

 
Jon said...

Nice concept

6:04 PM

 
anth0nyc said...

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

6:36 PM

 
Ian 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.

9:11 PM

 
Jack Chapple 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.

5:28 AM

 
fLUx 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

5:32 AM

 
XDrive 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

5:46 AM

 
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)

5:49 AM

 
Anonymous said...

Great website. Similar to WorldClockr

Best Regards

Dan

5:58 AM

 
Willem 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'.

6:16 AM

 
Misohoni Diary said...

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

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

6:41 AM

 
Alistair 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 >

6:55 AM

 
Anonymous said...

Those flash-headlines sure look ugly. They do not subject themselves to the operating systems font antialiasing, and also ignore the browsers font size settings. Try CTRL+scrollwheel (FF)!!
And why not use the unit "elements" (em) more in the CSS? The width of the center column could easy be set to em:s rather than pixels and then word wraps would look the same regardless of font size.

7:14 AM

 
skinrock 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 :)

7:20 AM

 
Anonymous said...

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

7:37 AM

 
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))

8:09 AM

 
Joost 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.

8:17 AM

 
skinrock 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?

8:55 AM

 
Björn said...

This is brilliant.

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

8:56 AM

 
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.

9:03 AM

 
Tippis 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.

9:11 AM

 
Jon 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)

9:35 AM

 
Nick 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.

9:35 AM

 
Andrew said...

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

9:46 AM

 
Michael 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.

9:59 AM

 
baxter said...

Good stuff!

I noticed that the links in your sidebar are not linking to the root dir. For example, if you are on this page and you click "Home" you are taken to /2007/03/index.html instead of /index.html.

10:36 AM

 
chaps said...

very sexy design

11:06 AM

 
Anonymous said...

see http://devshots.com

11:54 AM

 
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.

12:06 PM

 
mr-denali said...

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

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

12:10 PM

 
nathaniel said...

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

1:10 PM

 
Melissa said...

That is rather cool.

1:32 PM

 
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.

1:45 PM

 
Tim 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.

2:06 PM

 
kulpreet 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?

2:15 PM

 
Stephan 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.

2:56 PM

 
ed.freeman said...

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

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

2:59 PM

 
Doug Gottlieb said...

Very nice. Great idea & design

3:39 PM

 
Guillermo said...

This post has been removed by the author.

3:47 PM

 
Guillermo 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.

3:54 PM

 

Post a Comment

<< Home


   
SEE DEMO where one second == one hour