On a recent project we needed a way of scrolling a product listing nicley I came up with following.
Obviously there are probably a zillion ways of acheiving the same result but this is my take on it. I admit to not being any kind of genius when it comes to javascript/mootools so probably room for improvement but hey it works!
html
<div id=”wrapper”>
<div=”carosuel”>
<img src=”" />
<img src=”" />
<img src=”" />
</div>
</div>
<div=”right”></div>
css
width: x;
height: x
position: relative;
}
#carousel {
left: 0;
width: x;
}
javascript
var wrapper = $(‘wrap’); // The outer wrapper
var carousel = $(‘carousel’); // The inner wrapper
var items = $$(‘#carousel div’); // The different elements, this is an array
var item_width = 52; // The full width of a single item (incl. borders, padding, etc … if there is any)
var max_margin = item_width*items.length; //The width of the carousel elements with the wrapper
var allowScroll = true; //Allow scroll depending on with of carousel
var min_move = wrapper.getStyle(“width”).toInt() – max_margin + 10; //Work out the maximum margin to move the carousel to
//Check to see if the carousel is less then the wrapper if so don’t allow any scrolling
if (max_margin < wrapper.getStyle("width").toInt()) {
allowScroll = false;
}
// Set up the animation
var animation = new Fx.Tween(carousel, {duration: 1000});
// The function to browse forward(right)
function next_item(pos){
if(pos >= -max_margin){
animation.start(‘left’, 0);
}
}
// The function to browse backward(left)
function previous_item(pos){
if(pos <= 0){
animation.start('left', min_move);
}
}
// Set up the 'next' and 'previous' buttons only allow if allowScroll = true
$('left').addEvent('mouseover', function(){
if (allowScroll == true) {
var position = parseInt(carousel.getStyle('left'));
previous_item(position);
}
});
$('right').addEvent('mouseover', function(){
if (allowScroll == true) {
var position = parseInt(carousel.getStyle('left'));
next_item(position);
}
});
$('left').addEvent('mouseout', function(e){
animation.cancel();
});
$('right').addEvent('mouseout', function(e){
animation.cancel();
});
Post by: Richard
Tags: code, javascript, MooTools