1

I'm trying to use Malsup's jQuery Cycle plugin with jCarousel to allow thumbnails in my pagination to scroll horizontally and it's working fine. The problem is that sometimes the jcarousel plugin doesn't initialize because I believe the pagination is not ready yet. My code looks like this:

$('#slideshow').cycle({
    timeout : 0,
    speed   : 1000,
    pager   : '#image-carousel ul',
    pagerAnchorBuilder: function(idx, slide) {
        return '<li><a href="#"><img src="' + slide.src + '" width="107" height="80" /></a></li>'; 
    }
});

$('#image-carousel').jcarousel();

Sometimes when the page loads the jcarousel doesn't work, I used setTimeout to delay its initialization about 2 seconds and it worked every time so I assume it must be because sometimes the pager is not ready yet. I can live with the setTimeout solution for now but I think there must be a better way to handle this.

Javier Villanueva
  • 3,886
  • 13
  • 48
  • 80

1 Answers1

2

One way to get around it, if you're comfortable with altering the cycle plugin's source code, you could include a callback called onPagerBuilt (or something) to be run after the pagination is built. Alter the buildPager() function in cycle.js like so:

function buildPager(els, opts) {
    var $p = $(opts.pager);
    $.each(els, function(i,o) {
        $.fn.cycle.createPagerAnchor(i,o,$p,els,opts);
    });
    opts.updateActivePagerLink(opts.pager, opts.startingSlide, opts.activePagerClass);

        // add this line
        if (typeof opts.onPagerBuilt == 'function') opts.onPagerBuilt();
};

Then you'll want to add a default to $.fn.cycle.defaults somewhere in that list:

$.fn.cycle.defaults = {
  onPagerBuilt: null, // the callback to be run after pagination is built.

  // rest of the default options
  //...
}

Then your script would be like so:

$('#slideshow').cycle({
    timeout : 0,
    speed   : 1000,
    pager   : '#image-carousel ul',
    pagerAnchorBuilder: function(idx, slide) {
        return '<li><a href="#"><img src="' + slide.src + '" width="107" height="80" /></a></li>'; 
    },
    onPagerBuilt: function () {
        $('#image-carousel').jcarousel();
    }
});
Calvin
  • 8,697
  • 7
  • 43
  • 51