Mootools content slider – javascript

This is an old version of an improved Mootools Content Slider

I recently implemented a javascript based slider using MooTools. I’m increasingly becoming a huge fan of Mootools. Their documentation is great and the code I write just seems to be much cleaner. I don’t feel like it’s as fragile as js I’ve written in prototype/scriptaculous.

The content slider, which I pretty much implemented verbatim using Antonio Lupetti’s great tutorial at http://woork.blogspot.com/2009/01/elegant-animated-weekly-timeline-for.html.

Antonio’s tutorial is really great. It is missing two elements which I think improve the code base:

1) you have to set the number of elements to scroll explicitly

2) it does not handle some crazy user clicking like mad on either the left or right buttons

To solve both those pains, I’ve updated the code a bit to work with MooTools 1.2 and made a couple of enhancements seen below.

var totIncrement = 0;
var increment = 387;
var totalIncrements = $$("#sliderList li").length - 1
var maxRightIncrement = increment*(- totalIncrements);
 
var fx = new Fx.Tween('sliderList', {
   property: 'margin-left',
   duration: 1000,
   transition: Fx.Transitions.Back.easeInOut,
   onStart: function() {
      $("slide-left").removeEvents('click');
      $("slide-right").removeEvents('click');
   },
   onComplete: function() {
      appEvent();
   }
});
 
function appEvent() {
   // Previous Button
   $('slide-left').addEvents({
      'click' : function(event){
         if(totIncrement<0){
            event.stop();
            totIncrement = totIncrement + increment;
            fx.start(totIncrement);
        }
      }
   });
 
   // Next Button
   $('slide-right').addEvents({
      'click' : function(event){
         if(totIncrement>maxRightIncrement){
            event.stop();
            totIncrement = totIncrement - increment;
            fx.start(totIncrement);
        }
      }
   });
}
appEvent();

By encapsulating the right and left click events into its own function, I can easily turn on and off the events to prevent the end user from invoking the slide event in the middle of an event that may already be going on. A shorter way to say that is users can’t double click.

Secondly, creating the totalIncrements variable allows someone (like me) to add another list element into the markup at a later date without having to remember to update the javascript code.

These are just a couple of tweaks to an otherwise great tutorial. Thanks a lot Antonio and keep up the good work.

Tags: , , , ,