Revisit – jQuery Ad Rotator

2013-01-08

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:


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

The jQuery plugin:


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

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


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