I am working on a grid layout consisting of 9 divs nested in columns of three. The objective is that when the main grid (with ID #left) is clicked, two divs from the middle row (row="1") should have the class .show randomly applied to them. In the column where no class was applied, the div from the bottom row (row="2") should have the class .show applied instead. The image attached illustrates the possible random outcomes. It is important to note that the same outcome should never appear consecutively.
Included below is a snippet of the code I have written for this functionality. However, I am encountering issues with my index selection logic and have been unable to identify the root cause of the problem.
https://i.sstatic.net/EO24n.png
var obj = {
bindEvents: function() {
var _this = this;
$('#left').on("click", $.proxy(_this.interaction, _this));
},
interaction: function() {
var selector = this.randomGenerator(0, 3);
console.log('selector = ' + selector());
var $midRow = $('#left').find('div[row=1]');
var $bottomRow = $('#left').find('div[row=2]');
$midRow.removeClass('show');
$bottomRow.removeClass('show');
$midRow.not(':eq(' + selector() + ')').addClass('show');
$bottomRow.eq(selector()).addClass('show');
},
randomGenerator: function(min, max) {
var last;
console.log('last = ' + last);
return function () {
var random;
do {
random = Math.floor(Math.random() * (max - min)) + min;
} while (random === last);
last = random;
return random;
};
},
}
obj.bindEvents();
#left {
display: flex;
}
div[row] {
border: 1px solid black;
width: 20px;
background-color: yellow;
}
.show {
background-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="left">
<div col="0">
<div row="0">0</div>
<div row="1">1</div>
<div row="2">2</div>
</div>
<div col="1">
<div row="0">0</div>
<div row="1">1</div>
<div row="2">2</div>
</div>
<div col="2">
<div row="0">0</div>
<div row="1">1</div>
<div row="2">2</div>
</div>
</div>