Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change number of slides on bxslider depending on screensize

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,
    });
    }
like image 679
Ireally Rock Avatar asked Nov 27 '22 14:11

Ireally Rock


2 Answers

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,
});
like image 59
Nate Avatar answered Dec 09 '22 19:12

Nate


Here is a responsive solution that will dynamically adjust the settings as you resize the window:

var slider,
  oBxSettings = { /* Your bxSlider settings */ };

function init() {
  // Set maxSlides depending on window width
  oBxSettings.maxSlides = window.outerWidth < 430 ? 1 : 4;
}

$(document).ready(function() {
  init();
  // Initial bxSlider setup
  slider = $('#my-slider').bxSlider(oBxSettings);
});

$(window).resize(function() {
  // Update bxSlider when window crosses 430px breakpoint
  if ((window.outerWidth<430 && window.prevWidth>=430)
    || (window.outerWidth>=430 && window.prevWidth<430)) {
    init();
    slider.reloadSlider(oBxSettings);
  }
  window.prevWidth = window.outerWidth;
});
like image 26
thdoan Avatar answered Dec 09 '22 19:12

thdoan