preload image preload image preload image preload image preload image preload image preload image preload image preload image
The Official iSynergy Webdesign Blog

short url: http://isynergy.net/s/1

jQuery Tutorial: Rotating CSS using setInterval

jQuery is essentially a web designer’s dream. It’s a javascript library that makes it easy to write javascript code for web designers (at least that’s the way I see it). It’s built to be similar in structure to the way cascading stylesheets (CSS) are written. We here at iSynergy Webdesign use jQuery quite often to do many scripting events and effects.

What we’ll be doing today is setting an auto rotating CSS that swaps out after a certain amount of time. This effect can be used for a variety of things, such as changing the background along with some text styles.

See an example of the jQuery rotating CSS using setInterval.

In this example, we’ll be rotating 3 CSS files (style1.css, style2.css, and style3.css). To start off, we’ll need to set our first CSS onload.

<link href="styles/style1.css" rel="stylesheet" id="stylesheet" />

For the above code, please note that I added an id attribute. This is important because this will be the anchor reference for what we’ll be doing in a little bit.

Now, within the header still, but after the call of the jQuery library script (see How jQuery Works), we’ll start our script.

var interval
$(document).ready(function() {
	var r = Math.floor(Math.random()*3+1);
	$("#stylesheet").attr({href : "styles/style"+r+".css"});
	interval = setInterval("getCSS()", 5000);// 5 secs between requests
});
var currentStyle = $("#stylesheet").attr("href");

First we want to set a variable for the interval via var interval. This will be used a little bit below to call the function to swap the CSS after a certain amount of time.

After that, we’ll want to set the ready event that waits for the document to load before executing the script:

$(document).ready(function() {

//

});

Within that, the next few lines are where the script truly begins. The first line sets a variable to randomize a number. The count used to randomize can be altered by changing the digit that is represented by 3 within our code. We are using 3 in this case because that’s how many stylesheets we have. Feel free to change that for your personal needs.

The next line references the stylesheet anchor (the id we set earlier) and changes the href attribute to our randomized stylesheet. This way, a different stylesheet can be loaded each time the page is loaded.

The last line within the ready event is our timer. It calls a function, getCSS, every 5 seconds (represented by 5000 milliseconds). The amount of time can be changed by altering the milliseconds. We’ve set it on a short timer so it’s easier to see the effect.

After we close the ready event, we want to store the current stylesheet in a variable, which is represented by the last line. This variable will be used later when we rotate the stylesheet.

Now, we’ll write out our getCSS function, which will do the actual stylesheet rotation.

function getCSS() {
	if (currentStyle == "styles/style1.css") {
		$("#stylesheet").attr({href : "styles/style2.css"});
		currentStyle = "styles/style2.css";
	} else if (currentStyle == "styles/style2.css") {
		currentStyle = $("#stylesheet").attr({href : "styles/style3.css"});
		currentStyle = "styles/style3.css";
	} else {
		currentStyle = $("#stylesheet").attr({href : "styles/style1.css"});
		currentStyle = "styles/style1.css";
	}
}

We’ve added in an if statement so that when we rotate the stylesheet, we won’t rotate in a new stylesheet that is the exact one as the current stylesheet (because then, no change will be visible). So we do a check to see what the currentStyle variable (which stores what the current stylesheet href attribute is) is at the moment. If it is style1.css, then we swap in style2.css. After that, we set the new currentStyle variable to style2.css. Rinse and repeat until we’re done setting all 3 instances. That’s it.

The final script should look like the following (nested within a script tag):

<script type="text/javascript">
var interval
$(document).ready(function() {
	var r = Math.floor(Math.random()*3+1);
	$("#stylesheet").attr({href : "styles/style"+r+".css"});
	interval = setInterval("getCSS()", 5000);// 5 secs between requests
});
var currentStyle = $("#stylesheet").attr("href");

function getCSS() {
	if (currentStyle == "styles/style1.css") {
		$("#stylesheet").attr({href : "styles/style2.css"});
		currentStyle = "styles/style2.css";
	} else if (currentStyle == "styles/style2.css") {
		currentStyle = $("#stylesheet").attr({href : "styles/style3.css"});
		currentStyle = "styles/style3.css";
	} else {
		currentStyle = $("#stylesheet").attr({href : "styles/style1.css"});
		currentStyle = "styles/style1.css";
	}
}
</script>

One caveat for IE that is not related to the above script, if you intend on setting a background that spans the entire browser and swapping that background using the above script, you’ll need to add a few lines to your CSS to make sure the swap gets the intended effects. Mainly:

html { height: 100%; overflow: auto; margin: 0 }

body { height: 100%; overflow: auto; margin: 0 }

IE doesn’t seem to understand the dimensions for html and body unless it’s explicitly declared. As such, when the CSS rotation occurs, the effect doesn’t translate to the entire body of the page and only to the parts that have dimensions declared. The above should fix that problem.

Edit 2010/12/01: There seems to be a loading problem on some browsers (notably FireFox) that causes the page to display without any styles when it is rotating to a new CSS file. As such, we can get around this problem by pre-loading the CSS file. One method is detailed here: Preload CSS/JavaScript without execution. We’ve also updated our test files with the preload script.

Download jQuery rotating CSS using setInterval (zip containing all example files from above).


Share:

Share on LinkedIn     

Tags: , , , ,


5 Responses to “jQuery Tutorial: Rotating CSS using setInterval”

  1. Carlos Gozález Says:

    Hi, the code looks really interesting but when I tried it it showed some kind of bug. Sometimes for just a fraction of second the browser will show the website without a style and sometimes if you refresh the browser this will happen aswell. Any thoughts?
    Greetings!

  2. Jack Says:

    Hello Carlos,

    Thanks for bringing this up. We tried it and you’re right, it appears to be a problem, notably in FireFox. It seems to be a problem having to do with the lull between the page displaying and the CSS being downloaded and rendered. As such, the work-around for this would be to pre-load the CSS files. You can do this by following the instructions here: http://www.phpied.com/preload-cssjavascript-without-execution/. We’ve also updated our downloadable example, as well as our live example with the pre-load script. Thanks for the heads up. Let us know if you continue to have any problems.

  3. Jeff Says:

    This worked like a charm. hmmm, wonder if I can fade the change in?

  4. Jack Says:

    Hello Jeff,

    I’m not so sure about fading in the change. That would require fading the entire body of the page out, then fading it back in, I think. That’s the only way I can think of to do it. How that would be done is something that I can’t determine, though.

  5. Mike Says:

    This is really cool! Just what I was looking for. I’m re-designing a friends tanning salon website and this is exactly what I wanted the main graphic and supporting CSS to do. I’ll give it a try and report back. Thanks!

css.php