Search code examples
javascriptjqueryprototypejsowl-carousel

Passing a javascript variable to a jQuery plugin initilize function


I'm using the jQuery plugin "Owl Carousel" and am coming up on a weird problem when I try to initialize the plugin with a javascript variable as an option value.

Basically I have the following:

// thumbnail_count is the number of images in the slider, 
// already calculated elsewhere

var thumbnail_breakpoints = '';
switch (thumbnail_count) {
    case 3:
        thumbnail_breakpoints = '[0, 1], [219, 2], [299, 3]';
        break;
    case 2:
        thumbnail_breakpoints = '[0, 1], [219, 2]';
        break;
    case 1:
        thumbnail_breakpoints = '[0, 1]';
        break;
}
jQuery(function($) {
    $('#itemslider-zoom').data('owlCarousel').reinit({
        itemsCustom: [thumbnail_breakpoints]
    });
});

This doesn't work and the value of itemCustom is not passed correctly to the reinit functon. However if I manually enter a value for itemCustom is works complete as desired. For two images e.g.

jQuery(function($) {
    $('#itemslider-zoom').data('owlCarousel').reinit({
        itemsCustom: [[0, 1], [219, 2]]
    });
});

Can anybody help me solve why this is? Using javascript debugging I can see that thumbnail_breakpoints is definitely getting set correctly. Also if I change the switch case statements so each one does the jQuery function call directly with the required values it works fine, but that is a massive duplication of code.

Thanks in advance for any help.

P.S. This is within prototypejs, hence why jQuery is called in no conflicts mode.


Solution

  • Create 2-D array and pass it directly.

    Use

    var thumbnail_breakpoints = [];
    switch (thumbnail_count) {
        case 3:
            thumbnail_breakpoints = [[0, 1], [219, 2], [299, 3]];
            break;
        case 2:
            thumbnail_breakpoints = [[0, 1], [219, 2]];
            break;
        case 1:
            thumbnail_breakpoints = [[0, 1]];
            break;
    }
    jQuery(function($) {
        $('#itemslider-zoom').data('owlCarousel').reinit({itemsCustom: thumbnail_breakpoints});
    });