lundi 14 octobre 2019

Debugging jquery random variable issue

I built a jquery random display module for a recent web project, but it has a bug. It's meant to fill 4 grid tiles with a random div element, with a button that will load 4 new tiles. Occasionally it will only display 2 or 3 and I'm not sure why. :( See it in action at https://www.joytotheworldcoaching.com (About tab)

//Randomizer on CLICK $('#btnRandomizer').click(function() {

     var classList = [".randomLittleThings", ".randomJesusBeats", ".randomJoyJams", ".randomFavorites", ".randomQuotes", ".randomPhotos"];
     var randomClass1 = classList[Math.floor(Math.random() * classList.length)];
     var randomClass2 = classList[Math.floor(Math.random() * classList.length)];
     var randomClass3 = classList[Math.floor(Math.random() * classList.length)];
     var randomClass4 = classList[Math.floor(Math.random() * classList.length)];

     var random1 = $(randomClass1)[Math.floor(Math.random() * $(randomClass1).length)];
     var random2 = $(randomClass2)[Math.floor(Math.random() * $(randomClass2).length)];
     var random3 = $(randomClass3)[Math.floor(Math.random() * $(randomClass3).length)];
     var random4 = $(randomClass4)[Math.floor(Math.random() * $(randomClass3).length)];


     var color = ["rgb(245, 171, 153)","rgb(254, 180, 123)","rgb(255, 126, 95)", "rgb(212, 14, 204)", "rgb(113, 58, 166)"];
        var randomHeaderColor1 = color[Math.floor(Math.random() * color.length)];
        var randomHeaderColor2 = color[Math.floor(Math.random() * color.length)];
        var randomHeaderColor3 = color[Math.floor(Math.random() * color.length)];
        var randomHeaderColor4 = color[Math.floor(Math.random() * color.length)];

        $('.randomLittleThings').fadeOut('hide');
        $('.randomJesusBeats').fadeOut('hide');
        $('.randomJoyJams').fadeOut('hide');
        $('.randomFavorites').fadeOut('hide');
        $('.randomQuotes').fadeOut('hide');
        $('.randomPhotos').fadeOut('hide');

        $(random1).fadeIn('show');
           $('.randomLittleThings > .cardHeader').css({'background': randomHeaderColor1});
        $(random2).fadeIn('show');
           $('.randomJesusBeats > .cardHeader').css({'background': randomHeaderColor2});
        $(random3).fadeIn('show');
           $('.randomJoyJams > .cardHeader').css({'background': randomHeaderColor3});
        $(random4).fadeIn('show');
           $('.randomFavorites > .cardHeader').css({'background': randomHeaderColor4});

 });

It is supposed to display 4 fresh tiles each time the button is clicked but occasionally only displays 2 or 3. I'm wondering if it happens when the randomizer selects the same div twice?




Aucun commentaire:

Enregistrer un commentaire