November 10, 2009 : IN Guides & Tutorials

Combining Javascript setInterval and jQuery for lovely looping animations

Any designer worth his salt will be familiar with jQuery in one form or another.  The uber cool Javascript framework has become a staple of many a design studio worldwide and why not? Quite frankly Javascript frameworks don’t come much better or more importantly easier to learn than jQuery. What follows in this writeup however is a practical example of a native Javascript function that designers using jQuery or otherwise may never heard of let alone used.

This function goes by the name of setInterval. The reason why you, me or any other designer may never heard of setInterval is quite simple. When using a framework such as jQuery its  a great deal easier to just use it for what you need it for or use plug-ins and never really get into the nitty-gritty of’ ‘old school Javascript’. The majority of the time anything not contained within the jQuery docs. will be not be of particular interest to the majority of designers. Said designers, many times myself included, are under demand from clients to get whatever needs doing completed as quickly as possible and simply do just that.

A quick introduction to setInterval

setInterval is a Javascript function that waits for a set amount of milliseconds, executes a function and then repeats again based on the original millisecond time parameter. clearInterval is the antidote to this if you like and stops the original setInterval function when you require.

A similar set of Javascript functions are setTimeout and clearTimeout which differ slightly in there execution and therefore won’t be used in this tutorial. You may see both functions mentioned in other tutorials but seen as we are concentrating on looping animations setInterval is naturally the best choice for this tutorial.

Setting up the CSS/HTML …

So first thing to is get the initial HTML and CSS setup. All we are going to do here is set a holder div and three floated divs within. These three floated divs are going to be the elements we will loop through using setInterval.

The initial CSS

.cbox { display:block;margin:5px;background:blue;opacity:0.3;width:50px;height:50px;float:left; }
.active { opacity:1; }

The initial HTML

<div id="divhold">
<div class="cbox active"></div>
<div class="cbox"></div>
<div class="cbox"></div>
</div>

As you can now see from the first demo page we have a very simple setup, three blue boxed divs. One at full opacity and the remaining two faded out. Note – For Internet Explorer you will need to use the following code to achieve opacity control via css. I’ve left it out of the example code to save space. As a side note jQuery takes this into consideration when performing animations.

Opacity Control for Internet Explorer (30 = 0.3, 60 = 0.6 etc.)

filter: alpha(opacity = 30);

Also in the initial html/css we have added a class of active to the very first div, this will help us later on and also lets the browser know which to show as active first.

Starting the loop …

We now have the html in place but what we want to do is shift between all three of these boxes, each fading to full opacity whilst the one before it fades to the original opacity of 0.3.

This is where setInterval comes in. Now I’m sure this effect is achievable using the jQuery animation function which in itself is extremely powerful. The problem with the animation function is it becomes extremely messy extremely quickly. I’ve also found the jQuery animation function to be jittery when attempting to do too much with it.

So lets add the javascript in full to the second demo page and I’ll break it down below. You can now see that the boxes are sliding between full opacity and partial opacity in order. The animation will stop after the final div in our holder has passed but this forms the next part of the tutorial, don’t worry about that for now. The Javascript thus far then :

Complete Javascript to start animation off

function swapem(){

 var getnext = $("#divhold .active").next();
 $("#divhold div").fadeTo("slow", "0.3", function(){ $("#divhold div").removeClass("active");getnext.fadeTo("slow", "1").addClass("active") });

}

$(document).ready(function(){

 var divswap = setInterval('swapem()', 5000);

});

To break this down and explain a bit more about what’s happening here I’ll start with the very first Javascript function we’ve written – ‘swapem’ :

Just the initial ‘swapem’ function from the animation code above

function swapem(){

 var getnext = $("#divhold .active").next();
 $("#divhold div").fadeTo("slow", "0.3", function(){ $("#divhold div").removeClass("active");getnext.fadeTo("slow", "1").addClass("active") });

}

This is the main crux of the animation. Firstly it gets the next div to be animated and places this information in the ‘getnext’ variable. It does this by simply selecting the div after the one we currently have set to active, which of course has the class ‘active’ we added earlier. The next line in this function is where the actual animation takes place. Firstly each div within our holder is faded to an opacity of 0.3, when this is done each div in the holder div has the class ‘active’ removed and finally we use the ‘getnext’ variable which has already been set to add full opacity to the div we want to show. To finish it all off the div captured in the ‘getnext’ variable has the class name active added to it. At the moment this function hasn’t been called and isn’t doing anything, the next lines of Javascript are what starts everything off.

The document ready function that contains our use of setInterval

$(document).ready(function(){
	var divswap = setInterval('swapem()', 5000);
});

The document ready function you should already be familiar with. When the document is ready we create a variable that will hold the information of our setInterval function. At the same time the setInterval function begins running. It is instructed to run the ‘swapem’ function we first created every 5000 milliseconds. Both of these function parameters can be changed to whatever you would like them to be, for instance if our function went by a different name. Every 1000 milliseconds are equal to one whole second so our 5000 equals 5 seconds, 10000 would equal 10 seconds and so on.

Controlling the looping

So now in the second demo page we have a piece of Javascript working that starts a loop to animate the transition between opacity’s of 0.3 and 1 in order. At the moment however we have no genuine loop, once it gets to the last div in our holder it just stops. This is isn’t the fault of our setInterval, setInterval will just keep hitting the function every 5 seconds until we tell it to stop (which we’ll do later). The problem is with the ‘swapem’ function. When the function reaches the third div under the holder div there is no next div to find because it doesn’t exist. What we now need our function to do is recognise when its at the end of child divs and start from the beginning at this point.

Take a look at the third demo page. This page contains a few additional lines of Javascript in our ‘swapem’ function to get the currently active div, identified by having the class ‘active’. When the active div is identified we then check to see if it is the last element in the div holder, if it is we reset the ‘getnext’ variable to very first div in the holder. If it isn’t then the function carries on as normal looping through to the next div in line. This addition will now gives us animation looping continually.

Below is the revised ‘swapem’ function, nothing else on the third demo page differs from the second apart from the additional lines of code from line 4 to 7. This is what gives you the information a describing above.

Revised Javascript to detect end of loop and start over

function swapem(){

	var getnext = $("#divhold .active").next();
	var current = $("#divhold .active");
	if(current.is(':last-child')){
	var getnext = $("#divhold div:first-child");
	}
	$("#divhold div").fadeTo("slow", "0.3", function(){ $("#divhold div").removeClass("active");getnext.fadeTo("slow", "1").addClass("active") });

}

Stopping and Starting the loop

Now we have the loop working just as we want it we need a way to stop it. clearInterval takes care of this for us. We can use the clearInterval function anywhere we want it such as separate button away from the holder div or when a visitor mouses over one of the blue boxes. Take a look at the fourth and final demo page to see a number of different options to stop our loop and start it again.

clearInterval function

clearInterval(divswap);

The clearInterval function takes in the variable name we assigned to setInterval earlier and stops it completely. You can use the function on hover or click or any other Javascript you like.

clearInterval on mouseenter

$(".cbox").mouseenter(function(){
		clearInterval(divswap);
	});

To start it again we simply use the same function we used in the first document ready instance.

Original setInterval start code

var divswap = setInterval('swapem()', 5000);

This too can be dropped inside of any Javascript event.

Starting the loop again onClick

$(".start").click(function(){
	var divswap = setInterval('swapem()', 5000);
			return false;
	});

Applying this to sites in the wild …

I’m hoping this basic tutorial has given you a good starting point for something more advanced. The ‘blue boxes’ used in the demo pages of this tutorial could potentially be any style you wanted and could contain any number of child elements. The beauty of creating something like this from barebone code as provided here is that you don’t get plug-ins packed full of features that you’ll never need and you’ll always know where you are in the code.

If there are any questions feel free to ask away in the comments.

Demo Pages Recap :

Grab our RSS feed for more of the same ...

No Comments Yet, Care to leave one?

Add your comment