How do I make an animation of an icon that plays only when I hover on another Element?
I’m making a dumb project to better understand HTML, CSS and JavaScript (I’m a newbie).
I wanted to have an arrows that moves smoothly from right to left and vice versa on a loop when you hover on a link to which it points towards.
My HTML for this part looks roughly like this:
<div class='linkHeaderDiv'>
<a href='Something IDK.html' class='linkHeader'>Another page</a>
<script src="Arrow Animation.js"></script>
<svg class="arrowIconHeader" id="Livello_1" data-name="Livello 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33 34">
<defs>
<style>
.cls-1{fill:none;stroke:#000;stroke-linecap:round;stroke-linejoin:round;}
</style>
</defs>
<line class="cls-1" x1="0.5" y1="0.5" x2="32.5" y2="17.5"/>
<line class="cls-1" x1="0.5" y1="33.5" x2="32.5" y2="17.5"/>
</svg>
</div>
So far I tried to use CCS to create an animation that looks like this:
@keyframes arrowTransition{
from {transform: translateX(0%);}
to {transform: translateX(-20%);}
}
.linkHeader:hover .arrowIconHeader{
animation-name: arrowTransition;
animation-duration: 2s;
animation-direction: alternate;
animation-duration: infinite;
}
But I had no luck with this method, so I tried using JavaScript to write the following code:
const linkHeader = document.getElementsByClassName('linkHeader')
const arrowIconHeader = document.getElementsByClassName('arrowIconHeader')
function arrowAnimation(a) {
a.animate(
[{transform:'translateX(0px)'},{transform:'translateX(-20px)'}],
{duration:2000,iterations: Infinity,}
)
}
linkHeader.addEventListener('onmouseover',()=>{arrowAnimation(arrowIconHeader)})
But no matter what the arrow icon just won’t move.
Giorgio Giovanni Mattio is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.