jQuery Image Carousel

By sarah

Continuing with my jQuery study, I set myself the task of creating an image carousel with buttons that become deselectable on reaching the end of the reel.


First of all I started with what I know by writing the syntax for a series of divs containing the images and description text. In my stylesheet I displayed them inline, with a smaller overlay on top so that only one slide can be visible. I then had to get my jQuery to move these slides along into the visible area one at a time.

I learnt a variety of new things in this project, the most notable being the .animate function. This allowed me to create a smooth transition towards selected CSS properties. In this case I used the ‘right’ property to give the effect the carousel was sliding along.

I stumbled upon a few problems in this project. When setting and using variables to calculate the position of my current slide, I used the .css function to get the value of the ‘right’ attribute and stripped out the ‘px’. I had assumed this would then leave me free to use it in a mathematical operation but when this wasn’t the case it led me to discover ‘parseInt’. This allowed me to convert the css value from a string to a number so it could be used further in the formula.

The real head scratcher came when i went to browser test and found that the carousel didn’t work in Internet Explorer altogether. I narrowed this down to the ‘right’ value from my CSS. Where firefox was using 0 as a default for the css value, ie was using ‘auto’ which is of course a string hence the broken function. That’s certainly an ie quirk to remember.

For flexibility I plan to create this code as a plugin so that any user can customise variables for their own purpose.Feel free to take a look at my final carousel here and the jQuery that goes with it.

$(document).ready(function () {
$('.scroll#left').addClass("disabled");

var totalImages = $('.slide-container').size();
var currentImage = "1";

$('#container .scroll').click(function () {
if ($(this).hasClass("disabled")) {

}
else {

var scrollWidth = $('.slide-container').width();
var currentPosition = parseInt($('#images-inner').css("right").replace("px", ""));
var scrollAmountRight = currentPosition + scrollWidth;
var scrollAmountLeft = currentPosition - scrollWidth;
var direction = $(this).attr("id");

if (direction == "right") {
$('#images-inner').animate({ right: scrollAmountRight });
currentImage++;
}
else {
$('#images-inner').animate({ right: scrollAmountLeft });
currentImage--;
}
if (totalImages == currentImage) {
$('.scroll#right').addClass("disabled");
}
else if (currentImage == "1") {
$('.scroll#left').addClass("disabled");
}
else {
$('.scroll').removeClass("disabled");
}
}
});
});

Related posts