Switching FontAwesome Icons on Click with jQuery

FontAwesome is a wonderful tool. For those of you unaware, this is a library of icons available for use in your applications. The latest iteration (5.0 at time of writing) has provided a whole range of new features and thousands of icons that are endlessly useful. These are easily added into your application with some very simple code, all covered in great depth in their “Getting Started” guide.

Today, whilst working on a client application, I required a collapsible panel for some content. The client wanted an arrow icon that would open and close the panel and that icon needed to change to reflect whether the panel was open or closed. Two options were available here. I could either rotate the arrow icon or I could replace it with the available alternate icon in FontAwesome. I chose the latter. No particular reason here, either way is just as acceptable.

First thing to note is that the latest version of FontAwesome uses SVG images that are perfect for the modern web. This is important because trying to update the class on the icon will not work since the code you use gets automatically commented out and replaced with the SVG, so you need to search for that instead.

The second thing to note is that the class is not the defining attribute for the SVG icon, it’s actually a data attribute called ‘data-icon’.

Below is a function I applied to the buttons on my page to swap the icon over (I’ve used the caret icons but it could be any icon).


jQuery('button').click(function(){
var icon = jQuery(this).find('svg');
if(icon.attr('data-icon') == 'caret-right') {
icon.attr('data-icon', 'caret-down');
} else {
icon.attr('data-icon', 'caret-right');
}
});

That’s all you need. The function fires on all button clicks on the page so if you want to limit it to specific buttons then just use a class on those elements and add that class to the selector in the code above.

Let me know if you have any smart ways to improve on this or if you can think of alternative ways to handle this.