Creating a responsive jCarousel in Drupal

jCarousel is a very nice jQuery plugin that lets you create beautifull carousels with minimal code. The Drupal jCarousel module provides full integration with the jCarousel plugin : you can simply create a View of your images, select jCarousel as the style, and that's it : you have a carousel build from your Drupal content.

jCarousel is pretty responsive on it's own: it will automatically adapt when your carousel's width changes. There are some things it doesn't do however:

  1. Unless you set your carousel's dimensions in % - not always practical, in particular for vertical carousels - it won't adapt to the window being resized ;
  2. When the carousel's size changes it doesn't change the number of items by which it scrolls when you click next/previous.

Both of these can be easily fixed by adding some javascript. First, let's look at handling those resizes. All we need to do is catch the 'resize' event on the window, and then resize our carousel accordingly. In this example I have a vertical carousel, and the page has a #header and a #footer, the size of which is removed when calculating how much size is left for the carousel. So here is the code :

(function($) { 
  /* The resize event */
  $(window).resize(function() {
    var carousel_line = 110; /* Height of each carousel element + padding */

    var header_height = $('#header').height(); /* Height of the header section */
    var footer_height = $('#footer').height(); /* Height of the footer section */
    var viewport_height = $(window).height(); /* Viewport height */

    /* Calculate how many images will fit in the given height */  
    var cpp = Math.floor((viewport_height - header_height - footer_height )/carousel_line);

    /* And resize the carousel */
    $('.jcarousel-container, .jcarousel-clip').height(carousel_line * cpp);

  /* Make sure this gets called when the page first loads */
  Drupal.behaviors.mytheme = {                   
    attach: function(context, settings) {

That's it. jCarousel actually takes care of the rest - moving the prev/next arrows and so on. As mentioned the other thing jCarousel does not do is adapt the number of elements it scrolls by. If you scroll by one element each time that's not a problem - if you scroll by the entire number of visible elements each time then you need to modify this value. For this you need to know what is the associated id of your carousel - just inspect your document and look in the carousel's ul element, it will have a class looking like jcarousel-dom-1. Once you have that, It's only an extra three lines of code :

var jcarousel = $('.jcarousel-dom-1').data('jcarousel');
jcarousel.options.scroll = cpp;                     
$('.jcarousel-container, .jcarousel-clip').height(carousel_line * cpp);

You can add those three lines right after the line where 'cpp' is calculated in the first script. That's it - your carousel is now fully responsive !