Switch between icons when using FontAwesome 5.0 SVG Framework

Viewed 23046

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?

9 Answers

Didn't find any documentation about this. As it's not offically released yet, you can use this workaround (jQuery):

$('svg.fa-toggle-off').replaceWith('<i class="fas fa-toggle-on"></i>');

This is what I found worked best for me. I was using self-hosted Fontawesome v5.7.1

HTML (note two icons, one with .hidden class)

<a id="delete_btn" href="#">
  <i class="icon fas fa-trash"></i>
  <i class="spinner fas fa-spinner fa-spin hidden"></i>
  <div class="caption">Delete</div>
</a>

CSS

.hidden {
  display: none;
}

jQuery

$('#delete_btn').click( function() {
  var fa_icon = $('#delete_btn .icon');
  var fa_spin = $('#delete_btn .spinner');
  fa_icon.addClass('hidden');
  fa_spin.removeClass('hidden');

  //do something

  fa_spin.addClass('hidden');
  fa_icon.removeClass('hidden');
});

For a plain JS example (password reveal)

//event = mouse click
const passwordInput = event.currentTarget
    .closest('.input-group')
    .querySelector('input');
let icon = 'eye-slash';
let newType = 'text';

// type is text, set to password and change icon to eye
if (passwordInput.getAttribute('type') === 'text') {
    icon = 'eye';
    newType = 'password';
}
passwordInput.setAttribute('type', newType);
event.currentTarget
    .querySelector('svg')
    .setAttribute('data-icon', icon);

HTML

<button class="btn btn-primary" id="menu-toggle">
            <span id="menu-arrow-left" class='fa fa-fast-backward' aria-hidden="true"></span>
            <span id="menu-arrow-right" class='fa fa-fast-forward' style="display: none;" aria-hidden="true"></span>
        </button>

Jquery

$("#menu-toggle").click(function(e) {
      e.preventDefault();
      $("#wrapper").toggleClass("toggled");
      $('#menu-arrow-left').toggle();
      $('#menu-arrow-right').toggle();
    });

I feel this to be the most basic and aptful solution.

Related