Fix jquery/javascript small function

Job ID: 35079739

Budget: €8 – €20 EUR

We need a function to trigger a plugin (lightGallery.js - https://www.lightgalleryjs.com/) to display a lightbox gallery. We need to reuse the function in several places, so we call it using a data attribute on the DOM elements (data-gallery). This element, in addition to triggering the function, contains all the information needed to add the images to an array that is then used in the plugin call. So far everything seems to be fine, but when it comes to using the array in the plugin code, something goes wrong. If the same array is copied and pasted manually into a variable, then it works.

The job is to fix the bug (whatever it is), optimize the code as much as possible and make it work. For those who know how to do it, I don't think it is even necessary to share the files, directly with the function you should be able to correct it.

Please, if you don't see the bug directly in the code, don't send a bid. Thank you.


//CODE
var initGallery = function () {
$("[data-gallery]").each(function () {

var $this = $(this),
destination = $this.attr("id"),
order = $this.data("order") + "_",
count = $this.data("count"),
continent = $(".section-cabecera").data("continent") + "/",
folder = "/Content/img/destinations/",
path = folder + continent + order + destination + "/" + destination + "_";

var pictures = [];

for (var i = 1, limit = count + 1; i < limit; i++) {
pictures.push(" {src: '" + path + i + ".jpg' }");
}

/* Just to check that the array is correct */
console.log(pictures);

/* This returns manualArray as text */
var array = JSON.stringify(pictures.join()),
formatedArray = "[" + array.toString().replace('"', '').replace('"', '') + "]";

/* Pass the array to string just to create a manual variable and test it */
$("#result").html(formatedArray);


/* This Works. Is just the previous text copied and pasted */
var manualArray = [
{ src: '/Content/img/destinations/africa/04_namibia/namibia_1.jpg' },
{ src: '/Content/img/destinations/africa/04_namibia/namibia_2.jpg' },
{ src: '/Content/img/destinations/africa/04_namibia/namibia_3.jpg' },
{ src: '/Content/img/destinations/africa/04_namibia/namibia_4.jpg' },
{ src: '/Content/img/destinations/africa/04_namibia/namibia_5.jpg' },
{ src: '/Content/img/destinations/africa/04_namibia/namibia_6.jpg' },
{ src: '/Content/img/destinations/africa/04_namibia/namibia_7.jpg' },
{ src: '/Content/img/destinations/africa/04_namibia/namibia_8.jpg' }
]

/* LightGallery Plugin */
var gallery = lightGallery($this, {
dynamic: true,
mode: "lg-zoom-out",
loop: false,
download: false,
plugins: [lgAutoplay, lgFullscreen],
dynamicEl: pictures
});

document.getElementById(destination).addEventListener("click", function () {
gallery.openGallery();
});
});
}