Time-sensitive CSS

8

Posted on : 31-03-2009 | By : Japh

Have you ever wanted to load a specific stylesheet depending on what time it is? It is actually very easy to do!

View Demo

I’m using jQuery in this just because it makes it look a little simpler, it’s not much more complex to do without jQuery… but let’s face it, you’re probably already using jQuery anyway, so why not ;)

Make yourself a new file to put your javascript into, I’ve called mine “script.js”. Include the new javascript file by putting this line in your HTML <head></head> section with the following line:

<script type="text/javascript" src="script.js"></script>

Now open your “script.js” file, and put the following lump of code into it:

// This line depends on jQuery, and tells the browser to kick off this stuff once
// everything's fully loaded
$(document).ready(function () {
    // These two lines make set a Date variable with the current date and time
    var currentDate = new Date();
    var currentHour = currentDate.getHours();
 
    // Here we're creating a new <link /> to insert in the <head></head>
    var newCSS = document.createElement('link');
    newCSS.type = 'text/css';
    newCSS.rel = 'stylesheet';
 
    // This is where you can determine when to use which stylesheet.
    // If the current hour is before 9am or 8pm (or later), use "night.css"
    if (currentHour < 9 || currentHour >= 20) {
        newCSS.href = 'css/night.css';
    }
    // Otherwise, use "day.css"
    else {
        newCSS.href = 'css/day.css';
    }
    // This line actually does the deed, and attaches the selected stylesheet
    $("head").append(newCSS);
 
    // This line isn't necessary, it's just showing the actual time in the demo.
    $(".satellite").html(currentDate.toTimeString());
});

Read the commenting to understand what’s actually going on there, but that should do it! Easier than you thought, I bet :)

If you have any questions or suggestions, leave a comment!