Skip to content

Instantly share code, notes, and snippets.

@qmmr
Created February 21, 2012 21:32
Show Gist options
  • Save qmmr/1879101 to your computer and use it in GitHub Desktop.
Save qmmr/1879101 to your computer and use it in GitHub Desktop.
Basic image slider, procedural style
// basic slider, the procedural method
(function($) {
var $sliderNav = $('#slider-nav'),
$sliderUL = $('div.slider').css('overflow', 'hidden').find('ul'),
imgs = $sliderUL.find('img'),
imgWidth = imgs[0].width,
numOfImgs = imgs.length,
currentImage = 1,
totalImgsWidth = imgWidth * numOfImgs;
$sliderNav.show().children('button').on('click', function() {
var direction = $(this).data('dir'),
loc = imgWidth;
// update current
(direction === 'next') ? ++currentImage : --currentImage;
if (currentImage === 0) {
currentImage = numOfImgs;
loc = totalImgsWidth - imgWidth;
direction = 'next';
} else if (currentImage - 1 === numOfImgs) {
currentImage = 1;
loc = 0;
}
transition($sliderUL, loc, direction);
});
function transition(cont, loc, dir) {
var unit; // += ? -=
if (dir && loc !== 0) {
unit = (dir === 'next') ? '-=' : '+=';
}
cont.animate({
'margin-left': unit ? unit + loc : loc
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment