Search code examples
javascriptfor-loopfancybox

fancybox 3 in a for loop using $.fancybox.open


I would like to put all these fancybox calls in a loop

    var colors = [[
        {src  : 'http://example.net/red.jpg'},
        {src  : 'http://example.net/yellow.jpg'},
    ], [
        {src  : 'http://example.net/green.jpg',},
        {src  : 'http://example.net/black.jpg',},
    ]
];

$('.image-1').on('click', function() {
    $.fancybox.open(colors[0], {
        loop : true,
        protect: true,
        slideShow : {
            autoStart : true,
            speed     : 5000
        }
    });

    return false;
});

$('.image-2').on('click', function() {
    $.fancybox.open(colors[1], {
        loop : true,
        protect: true,
        slideShow : {
            autoStart : true,
            speed     : 5000
        }
    });

    return false;
});

In this mode it works well, but I want I solution like this one with a for cycle

for (var i = 0; i < 2; i++) {
    $('.image-'+(i+1).on('click', function() {
        $.fancybox.open(colors[i], {
            loop : true,
            protect: true,
            slideShow : {
                autoStart : true,
                speed     : 5000
            }
        });

        return false;
    });
}

this solution does not work, only if I set colors[0] or colors[1]

can you help me to fix this problem?

thanks


Solution

  • You should learn about one of the most important concept of JavaScript - Closures. There are numerous tutorials about this, for example - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures or https://medium.com/dailyjs/i-never-understood-javascript-closures-9663703368e8

    In your case, I would add some attribute to your links (for example, data-index) and use that from within click method to retrieve the corresponding data.