dimanche 27 novembre 2016

Prevent having more than two same attributes(srcset) when randomly changing attributes with jQuery

i made this script for grid gallery that changes images randomly one at the time every 3s, by changing its srcset attribute, theres allways 15 visible images but array is made out of 28 and since its random sometimes happens that there are 3 or more of the same image, theres chance to have all 15 be the same (crazy small chance but you get my point) and i want to prevent it somehow.

I was thinking about somehow defining that theres allways 2 same attributes possible at most, so it wont change other img to that attribute if there are 2 of those. Or if its possible, this would be perfect, to have only one of attribute visible and it wont add that to other img if there is exactly that attribute.

Im ok with having at most 2 of the same attributes since it will minimize chance of seeing them both at the same time since half is hidden and it will prevent seeig 3 or more.

Heres the jQuery:

$(function () {


    //array
    var dice = $('.attachment-lenslight_squares').map(function () {
        return $(this).attr('srcset')
    }).get();

    $('.attachment-lenslight_squares')
       .click(function () {

        var num = Math.floor(Math.random() * dice.length);
        $(this).fadeOut(200, function() {
            $(this).attr('srcset', dice[num]);
    }).fadeIn(200);
    });
    setInterval(function () {
        var rand = Math.floor(Math.random()* 15);
    $('.attachment-lenslight_squares').eq(rand).click();
}, 3000);

});

Thanks for ideas




Aucun commentaire:

Enregistrer un commentaire