I want to make the heart icon move up, turn red, move back down, and turn back to black when I click on it. I also want to keep track of how many times I’ve clicked on it.
My html
<div class="center">
<i class="fa-regular fa-heart" onclick="heartAnimation()"></i>
<p id="count">0</p>
</div>;
My css
@keyframes heart {
40% {
transform: translateY(-10px);
color: red;
}
95% {
transform: translateY(0px;);
color: red;
}
100% {
color: black;
}
}
.animation {
animation: heart 1s;
}
My Javascript
const icon = document.querySelector(".fa-regular");
const count = document.querySelector("#count");
count = 0;
function heartAnimation() {
icon.classList.add("animation");
count.innerText++;
}
I originally thought that I could add an onclick listener to the icon and add a class that would call the keyframe and keep count of the clicks. The click counter works fine, but I want it so that the animation is called every time that I click it. Right now, it moves up and down only on the first click. After that, the heart icon doesn’t move or change color – only the click counter changes.
2
Answers
you can do this through adding and removing animation class at the desired time.
to do this you can use jquery code:
or javascript (vanilla/pure):
also if you need special times for your animation to kick in or to be removed you need to use events and functions like scroll height, timeout, interval, onclick, .etc
Couple of things:
0
and try to increment it later in your function.let num = 0;
for the incrementing and then assign the number to the nodes textContent once you increment it from its previous value.Optionally you could also add a pointer-event in the CSS to remove any clicks while the animation is playing. You could also code in logic that would store the click and reset the animation on click.
Lastly I prefer adding event listeners using
.addEventListener
method.Some important notes about
.addEventListener
vsonclick=
from (MDN)