samedi 29 avril 2017

How to ensure only 2 divs are selected in javascript

I've done quite a bit of searching around and can't seem to find what I'm looking for so hoooopefully this isn't super repetitive. I'm making a pretty simple memory game in vanilla javascript (trying to stay away from jquery so I can get the basics of JS down)

Here's a link to the fiddle so you can see the whole works as well as the function I think is giving me the trouble: http://ift.tt/2pvCKyk

var showTile = function() {
var tile = document.getElementsByClassName('tile');
var tilesChosen = 0;
console.log(this.style.backgroundColor);
console.log(this);

if (tilesChosen < 2) {
    this.classList.remove('card-back');
    tilesChosen = tilesChosen + 1;
    console.log('under 2');
    console.log(tilesChosen);
}
else if (tilesChosen == 2) {
    tile.removeEventListener('click', function() {
        console.log('hit the max');
    })
}

};

and my problem here is that I can click on a tile, the card-back class is removed revealing the color but I can't figure out how to limit that to only 2 tiles.

My current train of thought goes something like this:

tilesChosen is set to zero
if statement checks if tilesChosen is < 2
if so, increment tilesChosen by 1
else, if tilesChosen == 2, then remove the event handlers on all the classes which I would think would stop anyone from overturning more than 2 tiles.

but so far I'm not even entering into the elseIf regardless of how many tiles you click. also, tilesChosen isn't incrementing beyond 1 so its like I'm stuck in the if part of the statement. I've also put this if/else inside for and while loops hoping to force it to loop through and test tilesChosen for its value but its the same thing.

any advice you guys have would be much appreciated!

Aucun commentaire:

Enregistrer un commentaire