Revisit – jQuery Ad Rotator


A while ago I received a comment on my old post Javascript – Ad rotator, saying that he wanted to use it on multiple ad rotators on his page. My old code was an example on how to make an ad rotator for only one instance, it was not really suited for multiple ones. So I thought I would address the request by making the same thing but as a plugin instead. And is there an easier way of doing this than by using jQuery? It makes it easy to make a plugin that can be used on multiple instances of ad rotators simultaneously.

This one works by showing a link in the selected container while it hides the others. After a set delay, it hides the active ad and displays the next one. You can style it however you want, put images inside the links, do whatever you want with them, as long as there are anchor elements (<a>) inside the selected container. In the section below, you find the code snippets to do this: the HTML markup, the jQuery plugin itself and an example of how to initiate the rotation. And remember you have to include jQuery on your site to run this.

HTML Markup:

<a href="#">link 1</a>
<a href="#">second link</a>
<a href="#">3:rd link</a>
<a href="#">link 1</a>
<a href="#">second link</a>
<a href="#">3:rd link</a>
<a href="#">Fourth ad</a>

The jQuery plugin:

$.fn.adRotator = function(options){
options = $.extend({
delay: 5000
}, options);
var $adContainer = $(this);
var $links = $adContainer.find('a');
$'adIndex', 0);
var nextIndex = ($'adIndex') < ($links.length - 1)) ? ($'adIndex') + 1) : 0;
$'adIndex', nextIndex);
}, options.delay);
return this;

This is how you initiate the plugin. Remember to run this when the document is ready.

$('.ads2').adRotator({delay: 3000});