CSS Switcher by month using Javascript

I’ve been creating a website where I wanted to change the look depending on the season.  I’ve used Javascript to control what CSS was applied by checking what month it is, then changing the href property of the css <link> tag.

Adding the default stylesheets to the HTML

I created one main CSS file, that held all the styles that will never change, as well as a four separate season CSS files for Summer, Autumn, Winter and Spring. I used the Summer css file as a default and added an id called season.

<link href="main.css" rel="stylesheet" type="text/css" />
<link id="season" href="summer.css" rel="stylesheet" type="text/css" />

Javascript code to select the CSS

Firstly I get the date, then use an if statement to set a variable with the correct filename. So, between December and February it will show winter.css, March to May spring.css, June to August summer.css and September to November autumn.css.

Then I just set the href property of the element with id ‘season’.

// Get CSS JavaScript Document
function getCSS()
{
datetoday = new Date();
themonth=datetoday.getMonth() + 1;


if (themonth == 12)
display = "winter.css";
else if (themonth <= 2)
display = "winter.css";
else if (themonth > 2 && themonth <=5 )
display = "spring.css";
else if (themonth > 5 && themonth <=8 )
display = "summer.css";
else if (themonth > 8 && themonth <=11 )
display = "autumn.css";


document.getElementById('season').href = display;
// End -->
}

Call the function

All that’s left to do is call the function in the<head> of the page.

<script type="text/javascript" language="javascript">
getCSS();
</script>

Done!

Tags: , ,

Leave a Reply