Custom Javascript Banner Rotator – Part 2: jQuery!

By in
No comments

As I suggested in part 1 of this series, I recently discovered the wonderful world of jQuery, the “write less, do more javascript library”. And sure enough, this is one tool that really lives up to its name! Not only can you do all sorts of neat (even useful!) javascript effects and events, but they are suprisingly easy to do! I had put learning this on the backburner a while back, but after publishing my Banner Rotator, I figured it was about time to bring that sucker front and center and start cooking!

The banner rotator script I posted yesterday presented the perfect opportunity to jump in. Using this incredible framework, not only was I able to wrap the functionality into a plugin, but I was able to improve and refactor it to make it reusable (which is a good thing because I’m going to be using it on the city’s Convention Center website). It turned out to be so easy, I don’t even have to waste time with a back story. Let’s go straight to the code!

First thing you want to do when making a jQuery plugin is create the function and assign it to jQuery. I’ve also included the (improved!) local variables from last time to keep track of where we are in the rotation.

.

var imgSrcs = [];
var curSrc = 0;

var imgElems;
var curElem = 0;

var fadeSpeed;
var imageTimeout;

function img(src, alt){
this.src = src;
this.alt = alt;
}

jQuery.fn.bannerswapper = function()
{};

Notice that I’ve created a class img to hold the image data, including source and alternate text attributes.

Now we want to provide a way for users to supply arguments for imageTimeout and fadeSpeed. In addition, this time, we’re going to be reading from an XML file which contains the list of images (along with their alt tags!) to build our list. Handling paramters is pretty straightforward:

jQuery.fn.bannerswapper = function(xmlFile, settings)
{
var banner = this;
settings = jQuery.extend({
fade: 6000,
timeout: 10000
}, settings);
}
fadeSpeed = settings.fade;
imageTimeout = settings.timeout;

the jQuery.extend allows us to declare the settings variables, including default values. In this case, fade is set to 6000ms, and timeout (time between frames) is 10000. If users supply parameters (as we’ll see later) then these default values will be replaced. Also note that because xmlFile is explicitly defined in the function signature, it is now a REQUIRED variable.

Next, we want to read the xml file, and create our array of elements. I cannot emphasize in words just how easy this is to do with jQuery, so I’ll let the code speak for itself:

// load image sources
$.get(xmlFile, function(xml)
{
var i = 0;
$(xml).find('image').each(function()
{
imgSrcs[i++] = new img($(this).attr('src'), $(this).attr('alt'));
});

// make sure there are at least 2 elements
if (imgSrcs.length < 2) return;

// only create element if it's not already there
if (banner.length == 1) banner.append(document.createElement('img'));

// get array of image elements to swap
imgElems = $('img', banner);

// start toggling!
toggle();
});

That is literally ALL there is to it! I create a new instance of the img class for each element in the xml file and append it to the array. Once the array is complete, we just call toggle and we’re on our way!

One thing I did discover was that my previous example did not handle situations where there are an ODD number of images. So below is an improved method which toggles the image back and forth, taking this into account:

function toggle()
{
// move to next image
if (++curSrc >= imgSrcs.length) curSrc = 0;

// grab ref to elements for updating
var frontImg = imgElems[curElem];
if (++curElem > 1) curElem = 0;
var backImg = imgElems[curElem];

// set current image to hide next
frontImg.className = "";
frontImg.removeAttribute('style');

// prepare to swap image
backImg.className = "show";
backImg.src = imgSrcs[curSrc].src;
backImg.alt = imgSrcs[curSrc].alt;

// fade in next image and repeat
setTimeout(function() { $('.show').fadeIn(fadeSpeed, toggle); }, imageTimeout);
}

Can you believe it’s really that easy? Now all we have to do is call our plugin, here is the syntax.

<asp:ScriptManagerProxy ID="ScriptManager" runat="server">
<
Scripts>
<
asp:ScriptReference Path="/files/scripts/jquery/jquery-1.2.6.pack.js" />
<
asp:ScriptReference Path="/files/scripts/jquery/bannerswapper/jquery.BannerSwapper.js" />
</
Scripts>
</
asp:ScriptManagerProxy>
<script type="text/javascript">
$().ready(function()
{
$('#banner_container').bannerswapper('/files/scripts/jquery/images.xml');
});
</script>
<
div id="banner_container">
<
img src="/images/banners/banner10.jpg" alt="" />
</
div>

Also note that I’ve moved all of the stylings to an external sheet so that needs to be included in your page header as well.

I’ve packed all the files I used (excluding the images) into a zip which I’ve uploaded to myBloop. If you’d like to take a look at the full source, please use the link below. Your comments are appreciated!

Download Banner Swapper jQuery Plugin

The following two tabs change content below.
Josh loves all things Microsoft and Windows, and develops solutions for Web, Desktop and Mobile using the .NET Framework, Azure, UWP and everything else in the Microsoft Stack. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom. His other passion is music, and in his spare time Josh spins and produces electronic music under the name DJ SelArom.