Louis
Louis

Reputation: 11

css/javascript multiple card flip: reset other cards

So I'm currently using this one: http://jsfiddle.net/nawdpj5j/10/

Now what I need is that when I flip one card (doesn't matter which one) and then flip another one the first one resets/turnes back.

I think I need to add something in here:

var init = function() {
var flippers = document.getElementsByClassName("flip");

for(i = 0; i < flippers.length; i++){
    flippers[i].addEventListener( 'click', function(){
        var cardID = this.dataset.targetid;
        var card = document.getElementById(cardID);
        card.toggleClassName('flipped');
}, false);
}


};

Thank you in advance!

Upvotes: 1

Views: 541

Answers (1)

dnapierata
dnapierata

Reputation: 1213

You can get an array of all flipped cards and flip them back whenever a card is flipped like so:

var init = function() {
    var flippers = document.getElementsByClassName("flip");
    for (i = 0; i < flippers.length; i++) {
        flippers[i].addEventListener('click', function() {
            var cardID = this.dataset.targetid;
            var card = document.getElementById(cardID);
            var flipped = document.getElementsByClassName('flipped');
            for (i = 0; i < flipped.length; i++) {
                if (card !== flipped[i]) {
                    flipped[i].toggleClassName('flipped');
                }
            }
            card.toggleClassName('flipped');
        }, false);
    }
};
window.addEventListener('DOMContentLoaded', init, false);

Here is a link to a working demo JS FIDDLE

Upvotes: 0

Related Questions