简体   繁体   中英

Change fontawesome icon/class when element is clicked

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM