Tutorial Different Stylesheet Pending the Time of Day

by in , 0

<script>
<!--
function getStylesheet() {
      var currentTime = new Date().getHours();
      if (0 <= currentTime&&currentTime < 5) {
       document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
      }
      if (5 <= currentTime&&currentTime < 11) {
       document.write("<link rel='stylesheet' href='morning.css' type='text/css'>");
      }
      if (11 <= currentTime&&currentTime < 16) {
       document.write("<link rel='stylesheet' href='day.css' type='text/css'>");
      }
      if (16 <= currentTime&&currentTime < 22) {
       document.write("<link rel='stylesheet' href='evening.css' type='text/css'>");
      }
      if (22 <= currentTime&&currentTime <= 24) {
       document.write("<link rel='stylesheet' href='night.css' type='text/css'>");
      }
}

getStylesheet();
-->
</script>

<noscript><link href="main.css" rel="stylesheet"></noscript>

Name your css files accordingly: night.css, day.css, etc... One cool bonus is that since JavaScript gets the time from the local machine instead of from the server, users will be served the time-based stylesheet based on their time, not the server's, which may be in a completely different timezone.

If JavaScript is disabled in the browser, it will default to the main.css stylesheet.

Leave a Reply