I start with one item in the stack ar
.
What I intended the code to do is: If user clicks the correct link (the one computer has randomly selected), we proceed to the next "level" where we add one more element to the stack.
In the next level user has to select 2 correct links in the order in which they're in the stack. Once user does that, he should proceed to the next level and so on. It's similar to Simon says game and I am just trying to imitate the bare logic of the game with this.
HTML:
<a href="javascript:void(0);" id="l1">Link 1</a>
<a href="javascript:void(0);" id="l2">Link 2</a>
<a href="javascript:void(0);" id="l3">Link 3</a>
<a href="javascript:void(0);" id="l4">Link 4</a>
<div id="log"></div>
Javascript
function check() {
var index = 0;
$('body').click(function(event) {
var log = $('#log');
alert(index);
if ($(event.target).is(ar[index])) {
log.html(index + ' ' + event.target.id + ' was clicked.');
index++;
if (index === ar.length) {
//if all clicked elements corresponded to correct
//order in array and reached end of array
level +=1;
console.log("Passing to next level. ", level);
randomId();
console.log(ar);
log.html(ar);
check();
}
}
else {
log.html(index + ' ' + event.target.id + ' was clicked. Is wrong');
index = 0;
}
});
}
var ar = [];
divIds = ["#l1", "#l2", "#l3", "#l4"];
level = 1;
randomId();
check();
function randomId() {
var min = 0;
var max = 3;
var id = Math.floor(Math.random() * (max-min+1)) + min;
var selectedId = divIds[id];
ar.push(selectedId);
alert(ar);
}
However when I am calling check()
function a second time (when we move to level 2 where there are 2 elements in stack) the value of index is not 0 despite the fact that var index = 0
is the first line of the check() function.
I am using console.log and alert to capture the value of index but their sheer number is confusing me. And by looking at the number of alert pop-ups, my check function seems to be acting like a loop. Why aren't we getting a clean slate when we're calling the function a second time?