I'm trying to apply my fade transition every time I click the button.
What is the best practice to achieve this?
So instead of .addClass() and then .removeClass() after it is added, imagine something like .apply() that would just apply the class once so it doesn't "keep" the class.
Right now I have .toggleClass which only applies the transition every other click (basically like: addClass, removeClass, addClass, and so on). I can think of doing it another way by looking to see if it already has the class, and if not, then remove it and add it again, but it seems so counter-intuitive and makes me think there must be a simpler and cleaner way to do this.
$("#btn").click(function() {
$("#cat").toggleClass("fade");
})
@import url('https://fonts.googleapis.com/css?family=Yatra+One');
body,
html {
height: 100%;
width: 100%;
margin: 0;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #eee;
}
.generator {
height: 400px;
width: 400px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
#cat {
height: 300px;
width: 400px;
border-radius: 5px;
transform: scale(1);
opacity: 1;
}
.fade {
animation: fade .5s linear forwards;
}
@keyframes fade {
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(0);
opacity: 0;
}
100% {
transform: scale(1);
opacity: 1;
}
}
#btn {
height: 90px;
width: 400px;
outline: none;
border: none;
border-radius: 5px;
background-color: #4682B4;
color: white;
font-size: 1.75em;
font-family: Yatra One;
transition: background-color 0.1s ease-in-out;
}
#btn:hover {
cursor: pointer;
background-color: #508EC3;
}
#btn:active {
background-color: #4293D8;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="generator">
<img id="cat" src="https://i.imgur.com/RVQZ9UM.png" alt="cat" />
<button id="btn">New cat</button>
</div>
</div>