Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a flip effect

I have the following code to create a flip image where I want the image to show a flip effect when user click it.

let img = document.querySelector('img')
let div;
let click = 0;
   img.onclick=function(){
   console.log(click)
   if(click %2 ==0){
  div = document.createElement('div')   
  document.body.appendChild(div);
  div.className = 'flip'
    div.textContent= 'Wikipedia'
  img.style.display = 'none'
  }else{
  img.style.display = 'revert'
  div.remove()
  }
  click++
}
@keyframes fliping{
from{
transform: rotateY(0deg);
}to{
transform: rotateY(180deg);
}
}
img{
width:100px;
height:70px;
position:absolute;
top:20px;
left:20px;
text-align:center;
line-height:70px;
}
.flip{
position:absolute;
top:20px;
left:20px;
width:100px;
height:70px;
background:grey;
 animation-name: fliping;
   animation-duration: 1s;
}
<img src='https://blogs.stthomas.edu/english/files/2016/04/Wikipedia-Logo.jpg'>

I try to use keyframe to do that. However, there are two problems with my code:

The text will flip as the element flips.

I am unable to click the img again to flip back since I make the img tag to become display:none.

Could anyone tell me how could I solve the problem or provide me a better solution to trigger a flip effect?

Thanks for any responds!

like image 942
James Avatar asked Oct 16 '25 04:10

James


1 Answers

You should use opacity instead of display.

let img = document.querySelector('img')
let div;
let click = 0;
   img.onclick=function(){
   console.log(click)
   if(click %2 ==0){
  div = document.createElement('div')   
  document.body.appendChild(div);
  div.className = 'flip'
    div.textContent= 'Wikipedia'
  img.style.opacity = '0'
  }else{
  img.style.opacity = '100'
  div.remove()
  }
  click++
}
@keyframes fliping{
from{
transform: rotateY(0deg);
}to{
transform: rotateY(180deg);
}
}
img{
width:100px;
height:70px;
position:absolute;
top:20px;
left:20px;
text-align:center;
line-height:70px;
z-index: 2;
}
.flip{
position:absolute;
top:20px;
left:20px;
width:100px;
height:70px;
background:grey;
 animation-name: fliping;
   animation-duration: 1s;
}
<img src='https://blogs.stthomas.edu/english/files/2016/04/Wikipedia-Logo.jpg'>