BySplitDecision Posted September 7, 2019 Share Posted September 7, 2019 Good evening, I have 9 divs in a grid on a page and I also have a button. What I want to achieve is when I click the button, it chooses 3 random divs and changes their background colour to red. I have wrote this code so far but it is buggy. I think it's because it's getting the same random number in the for loop. I've put my code below and I hope someone can point me in the right direction please. <div class="row"> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> <div class="col-sm-4"> <div class="box"></div> </div> </div> <script> $(function(){ $('button').click(function(){ var box = $('.box'); $(box).css('background','none'); var num; for (num = 0; num < 3; num++) { var result = Math.floor(Math.random()*box.length+1); console.log(result); $(box[result-1]).css('background','red'); box.splice(result,1); } }); }); </script> Thank you in advance for any help. BSD Quote Link to comment https://forums.phpfreaks.com/topic/309196-change-background-divs-on-click/ Share on other sites More sharing options...
BySplitDecision Posted September 7, 2019 Author Share Posted September 7, 2019 Hi guys, I managed to get it working in case anyone wants to know and do the same in future. So I added a while loop within the for loop to check to see if the box has a red background already) and while that is true, keep generating another random number. So the jQuery now looks like this: <script> $(function(){ $('button').click(function(){ var num; var box = $('.box'); $(box).css('background','none'); for (num = 0; num < 3; num++) { var result = Math.floor(Math.random()*box.length+1); var color = $(box[result-1]).attr('style'); while(color == 'background: red;') { result = Math.floor(Math.random()*box.length+1); color = $(box[result-1]).attr('style'); } $(box[result-1]).css('background','red'); box.splice(result,1); } }); }); </script> Many thanks, BSD Quote Link to comment https://forums.phpfreaks.com/topic/309196-change-background-divs-on-click/#findComment-1569478 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.