change number of slides on bxslider depending on screensize

Ireally Rock picture Ireally Rock · Apr 11, 2013 · Viewed 17.2k times · Source

I want to change the max number of slides on the bxslider for when my screen is below 430px.

I could use the below but this seems like overkill having to declare everything twice. Is there any other way that someone could think of?

    if ( $(window).width() < 430) {
    var myslider = $('#my-slider').bxSlider({
        ...
        maxSlides       : 1,
    });  
    }

    else {
    var myslider = $('#my-slider').bxSlider({
        ...
        maxSlides       : 4,
    });
    }

Answer

Nate picture Nate · Apr 11, 2013

You can make things less repetitive by setting a maxSlides variable, rather than repeating your slider code.

var maxSlides,
    width = $(window).width();

if (width < 430) {
    maxSlides = 1;
} else {
    maxSlides = 4;
}

var myslider = $('#my-slider').bxSlider({
    ...
    maxSlides: maxSlides,
});

You could make it even simpler with a ternary operator, though trying to get too concise is not necessarily a benefit.

var width = $(window).width();

var myslider = $('#my-slider').bxSlider({
    ...
    maxSlides: (width < 430) ? 1 : 4,
});