Change fontawesome icon/class when element is clicked

Viewed 352

I have an icon <i id="test" class="fas fa-times-circle"></i>

That when clicked, I'd like to change it's classes in order to become <i id="test" class="far fa-times-circle"></i>

So basically remove fas and add far, or vica versa if clicked again.

https://jsfiddle.net/bobbyrne01/ptsgba1h/7/

HTML:

<i class="fas fa-times-circle"></i>
<i class="far fa-times-circle"></i>
<hr/>

<div>
  <i id="test" class="fas fa-times-circle"></i>
</div>

Javascript:

$(document).ready(function() {
  $('#test').on('click', function() {
    console.log(this);
    $(this).toggleClass('fas');
    $(this).toggleClass('far');
  });
});

Any ideas why the classes are not being toggled?

2 Answers

you are using awesome version SVG with JavaScript which replaces <i> tags (and others) matching a set of criteria with <svg>

so , in your case change data-prefix attr to be fas Or far

here is a full example

$(document).ready(function() {
  $(document).on('click','#test', function() {
    console.log(this);
    //$(this).data("prefix",$(this).data("prefix")== 'fas' ? 'far' : 'fas')
    $(this).attr("data-prefix", function(index, attr){
      return attr == 'fas' ? 'far' : 'fas';
   })
  });
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/js/all.min.js"></script>
<i class="fas fa-times-circle"></i>
<i class="far fa-times-circle"></i>
<hr/>

<div>
  <i id="test" class="fas fa-times-circle"></i>
</div>

The <i> elements are replaced with svg elements based on the fa-* class when used with far / fas, and they contain classes of this kind: svg-inline--fa fa-times-circle fa-w-16. This is the reason the class toggle code does not work

A better solution would be to show / hide the appropriate icon on click.

Related