attach a variable to each instance of BX slider generated in an .each() statement
-
26-10-2019 - |
Question
I have some jQuery that creates a slideshow using BX slider for an unknown number of galleries. The markup is output by a PHP CMS and so we can't be confident of the number of galleries we will need on a page.
$(function () {
// Use a class rather than an ID
var $slider = $('.gallery');
// For each result
$slider.each(function (index, element) {
// If there is more than 1 image
if ($(element).find('img').length > 1) {
// Initialise a slider using the current index value
$slider.eq(index).bxSlider({
auto: false,
pager: false,
duration: 500
});
}
});
});
In order to use the public functions I need to define each instance of the BX slider as a variable.
So var slider = $('#gallery').bxSlider();
would be the norm. How can I generate these variables on the fly within this each statement?
Solution
Are you looking for something like this?
$(function () {
var bxSliderInstances = {};
// Use a class rather than an ID
var $slider = $('.gallery');
// For each result
$slider.each(function (index, element) {
// If there is more than 1 image
if ($(element).find('img').length > 1) {
// Initialise a slider using the current index value
bxSliderInstances["slider" + index] = $slider.eq(index).bxSlider({
auto: false,
pager: false,
duration: 500
});
}
});
});
bxSliderInstances
will contain all the slider instances as an associative array which you can use as per your need.
E.g bxSliderInstances.slider1
or `bxSliderInstances["slider1"]
will give you the first bxSlider
instance.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow