Auto-center images for jQuery Tools’ Scrollable

One of the jQuery Tools I really like is Scrollable. It is this beautiful and smooth image scrolling library that’s also easy to implement. Its out-of-box mouse wheel feature is also terrific.

If all the images in the gallery are in the same size, then everything easily got centered and nicely positioned. However, if I have a sequence of images that are in various widths, then they can’t be positioned center in the scrollable field. So after some experimenting with a tiny bit of Math, I’ve come up with the following solution:


$(document).ready(function() {
    //initialize scrollable
    $(".scrollable").scrollable();

    var api = $("#scrollable").data("scrollable");

    api.onSeek(function() {

    var index = this.getIndex();
    var scrollwidth = $("#scrollable").width();
    var imgwidth = $("#scrollable .items div").eq(index).width();
    var pos = $("#scrollable .items").position();

   //calculate new position value based on current image width
    var newpos = pos.left + 0.5*(scrollwidth - imgwidth);

    if(index >= 1 && index != 0) {
    //Update position with new value
    $("#scrollable .items").animate({left: newpos}, 250);
    }
    }); //End of api.onSeek

 }); //End of Document 


The HTML set up will be something like this:


<div class="scrollable" >
 <div class="items">
 <div><img src="images/morgank1.png" /></div>
 <div><img src="images/morgank2.png" /></div>
 <div><img src="images/morgank3.png" /></div>
 <div><img src="images/morgank4.png" /></div>
 </div>
</div>


DEMO
Note: This experiment works stably on Safari, Chrome, Opera and Firefox 4. It is not quite stable on Firefox 3.6 or below and it has not been tested on IE.

Due to the delay of position shift after each scroll, this may not be the ideal solution. I read on a forum that the auto-center feature was included in previous versions of Scrollable; however, it seems like it was taken off for some reasons. Hopefully it will be included again in later versions.