I’m trying to add a shake effect to a font-awesome icon whenever hovering over the hyperlink beside it.
The HTML looks like this:
<div class="icon-hyperlink">
<span>
<i class="fas fa-phone p-2"></i>
</span>
<span>
<a href="tel:XXXX XX XX XX">John: XXXX XX XX XX</a>
</span>
</div>
I’m trying to add the class fa-shake to the matching i with class "fas", and remove it when not hovering.
I’m not super well versed in jQuery, but I read a lot of the documentation and other stackoverflow articles getting this to work, to no avail.
My current code is:
$(document).ready(function() {
$(".icon-hyperlink a").hover(function(e) {
e.target.closest(".fas").addClass("fa-shake");
}, function(e) {
e.target.closest(".fas").removeClass("fa-shake");
});
});
The error I’m getting is:
Uncaught TypeError: Cannot read properties of null (reading ‘addClass’)
I also tried the following:
$(e.target.closest(".fas")).addClass("fa-shake");
That gives me no errors, but it also doesn’t work.
3
Answers
You need to traverse up to a shared parent, then find the icon
As mentioned above, the
<span>
elements seem unnecessary and just complicate the matter.Also, it’s 2022 and you probably don’t need jQuery.
You can use
.parents()
and.find()
instead to select the.fas
element you’re trying to find.Just ignore the html and css changes I made, they’re only there to demonstrate the js. Instead of shaking, the
.fas
element turns red.This can be achieved with no javascript and a little detective work of what FA uses behind the scenes.