J.Perrone J.Perrone - 7 months ago 21
HTML Question

Only the first card will flip

I want to make a photo gallery that flips the picture on click or tab, when flipped the user will get more information about the picture itself and a link. I have posted my entire CSS, JS and HTML so I hope that anyone will be able to spot my error.

JS:

$('#flip').on('click', function() {
$(".card", this).toggleClass("flipped");
});


HTML:

<div id="flip" class="flip">
<div class="card">
<div class="face front">Front</div>
<div class="face back">Back</div>
</div>
</div>
<div id="flip" class="flip">
<div class="card">
<div class="face front">Front</div>
<div class="face back">Back</div>
</div>
</div>


CSS:

.flip {
perspective: 800;
width: 100%;
height: 200px;
position: relative;
margin: 50px auto;
}

.flip .card.flipped {
transform: rotatex(-180deg);
}

.flip .card {
width: 100%;
height: 100%;
transform-style: preserve-3d;
transition: 0.5s;
}

.flip .card .face {
width: 100%;
height: 100%;
position: absolute;
backface-visibility: hidden;
z-index: 2;
font-family: Georgia, 'Times New Roman', Times, serif;
font-size: 3em;
text-align: center;
line-height: 200px;
}

.flip .card .front {
position: absolute;
z-index: 1;
background: $da_grey;
color: $white;
cursor: pointer;
}

.flip .card .back {
transform: rotatex(-180deg);
background: #121212;
color: $white;
cursor: pointer;
}

Answer

It is because you are duplicating ID value, which is supposed to be unique. Change it to:

<div id="flip1" class="flip">
    <div class="card">
        <div class="face front">Front</div>
        <div class="face back">Back</div>
    </div>
</div>
<div id="flip2" class="flip">
    <div class="card">
        <div class="face front">Front</div>
        <div class="face back">Back</div>
    </div>
</div>
$('#flip1, #flip2').on('click', function() {
    $(".card", this).toggleClass("flipped");
});

It is better to use classes for this:

$('.flip').on('click', function() {
    $(".card", this).toggleClass("flipped");
});

But make sure you don't duplicate IDs.

Comments