Home » Jquery » jquery – How do I change font awesome icon and button class onclick?

jquery – How do I change font awesome icon and button class onclick?

Posted by: admin February 22, 2020 Leave a comment

Questions:

How do I change button class and font-awesome icon onclick? When I click on the button the class and icon should be changed and vice versa.

<button type="button" id="btn_hideshow" data-id="{{$user->id}}" class="btn btn-primary btn-sm btn_hideshow">
  <i class="fa fa-eye"></i>
</button>
$(function() {
  $(".btn_hideshow").click(function() {
    let id = $(this).data('id');
    $.ajax({
      url: "/user-hide-show/" + id,
      method: "POST",
      data: {
        'id': id
      },
      dataType: "json",
      success: function(data) {
        if ($("button#btn_hideshow").hasClass() == "btn btn-primary btn-sm") {
          $("button#btn_hideshow").removeClass("btn btn-primary btn-sm").addClass("btn btn-info btn-sm")
            .append().html("<i class='fa fa-eye-slash'><i/>")
        } else {
          $("button#hideAndShow").removeClass("btn btn-info btn-sm").addClass("btn btn-primary btn-sm").append().html("<i class='fa fa-eye'><i/>")
        }
      }
    });
  });
});
How to&Answer:

Assuming your AJAX call is working then the issue is in the if statement. hasClass() returns a boolean value, yet you’re trying to compare that to the class string to search for. Instead the string needs to be provided as an argument to the function, eg:

if ($("button#btn_hideshow").hasClass("btn-primary") {   

That being said, there’s a better way to do what you require.

As the btn and btn-sm classes are always present on the element they can be removed from your logic. All you then need to do is toggle the btn-primary and btn-info classes on the button. Similarly the child <i> element can be kept instead of removed/re-added, and the fa-eye and fa-eye-slash classes can be toggled. As such, try this:

// outside AJAX callback:
let $button = $("#btn_hideshow");

// inside AJAX callback:
$button.toggleClass('btn-primary btn-info').find('i').toggleClass('fa-eye-slash fa-eye')