I'm looking to be able to switch between icons in Javascript while using the new FontAwesome SVG framework.
Previously in the old WebFont method, this was achieved by toggling or changing the class on the tag, however as these are now rendered as SVG's in the source code this no longer works.
Is there a way to do this without needing to render both SVG icons in source code and using additional classes/CSS to toggle display?
Assuming you are using the recommended method with the fontawesome.js sheet, I found this on the official documentation:
Changing icons by changing class:
Verified with FA 5.0.2
I modified the original documentation found on Font-Awesome's website here. The selector on their website wasn't selecting the proper element, so we need to modify the attribute.
HTML
The class of the div doesn't really matter so much as we can change it. Looking at the javascript, we are using the element to find the svg and specifically, we are looking for the data-icon attribute. Once we know the data attribute, we can change it every time it is clicked.
So in this case, it starts off with the minus-square. If the icon is the minus-square, it changes it to the plus-square. If it is not the plus-square, it will change it to the minus-square.
JQuery
Verified with FA 5.0.0 using the recommended JS method for loading icons
HTML
This is what the HTML code looks like once the page is rendered, prior to a click:
JQUERY (on click used)
This will change the icon from eye-slash to eye.
Edit: Dec 20, 2017
As of Font Awesome 5.0.1, when using the Javascript version you can now add/remove classes as before, it just needs to be on the svg element rather than the original element (assuming i).
Updated code:
Also note that any applied ids or classes to the font awesome element will be brought over to the svg. Thus if you have
<i id='eyecon' class='eyecon fa fa-eye'>
then it will render the<svg id='eyecon' class='eyecon'>
.I had the same problem as well, and I found (after scrolling right to the very end) that the FontAwesome website states the following:
To do so, just the
FontAwesomeConfig
object and setautoReplaceSvg: 'nest'
.For a plain JS example (password reveal)
Didn't find any documentation about this. As it's not offically released yet, you can use this workaround (jQuery):