user6002037
user6002037

Reputation:

implementing flipcard on click instead of on hover

I have implemented a css flipcard effect, which works on hover using css. See css code below. However I want to implement the flipcard effect on click by using jQuery. I have tried everything but cannot figure it out.

Here is the javascript that I thought would work.

$('.flip-container .flipper').click(function(){
    $(this).css('transform, rotateY(180deg)');
});

Please see below for code that works with hover.

html

<div class="flip-container">
  <div class="flipper">
    <div class="front artist-1">
      <!-- front content -->
    </div>
    <div class="back">
      <p>You won</p>
    </div>
  </div>
</div>

css

/* flip the pane when hovered */
.flip-container:hover .flipper, .flip-container.hover .flipper {
  transform: rotateY(180deg);
}

.flip-container, .front, .back {
  width: 250px;
  height: 250px;
}

/* flip speed */
.flipper {
  transition: 0.8s;
  transform-style: preserve-3d;
  position: relative;
}

/* hide back of pane during swap */
.front, .back {
  backface-visibility: hidden;
  position: absolute;
  top: 0;
  left: 0;
}

/* front pane, placed above back */
.front {
  z-index: 2;
  transform: rotateY(0deg);
}

/* back, initially hidden pane */
.back {
  transform: rotateY(180deg);
  background-color: #fff;
}


.artist-1 {
  background: url(http://img.bleacherreport.net/img/images/photos/003/556/940/edab30087cea36c0ca206fc61a4b10fa_crop_north.jpg?w=630&h=420&q=75) center center no-repeat;
  background-size: cover; 
}

Upvotes: 6

Views: 13468

Answers (2)

Max Novich
Max Novich

Reputation: 1169

what you need to do is to change your css from being triggered on :hover pseudo element to a class which you need to toggle via jquery.

css

/* flip the pane when clicked */
 .flip-container .flipper.flip {
  transform: rotateY(180deg);
}

JS

$('.flip-container .flipper').click(function(){
    $(this).toggleClass("flip");
});

here is a working Fiddle

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337691

To make this work you need to remove the :hover rule on the .flip-container element in your CSS:

/* .flip-container:hover .flipper, */
.flip-container.hover .flipper {
    transform: rotateY(180deg);
}

Then in your JS you need to toggle the hover class when the element is clicked instead:

$('.flip-container .flipper').click(function() {
    $(this).closest('.flip-container').toggleClass('hover');
    $(this).css('transform, rotateY(180deg)');
});

Working example

Note that it may also be worth changing the class name from hover now too, otherwise it may get confusing when you come to maintain the code at a later date

Upvotes: 5

Related Questions