Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery toggle full class name

I am trying to toggle the class name of an icon in jQuery.

I'm using the font-awesome library, and it only replaces the initial "fa" in my class, here is my jsfiddle

$('[name="caret"]').click(function() {
    $(this).toggleClass('fa fa-caret-up fa-1x');
});

JSFiddle

like image 214
Arthur Avatar asked Feb 28 '26 17:02

Arthur


2 Answers

Well it is not changing to fa-caret-up because you are also toggling the class fa, which is mandatory for font awesome library to realize that it is an icon.

So just do

        $('[name="caret"]').click(function() {
            $(this).toggleClass('fa-caret-up fa-caret-down');
        });

This will remove the fa-caret-down class and will add fa-caret-up class.

Updated Fiddle

like image 105
void Avatar answered Mar 03 '26 07:03

void


Instead just use this:

$(this).toggleClass('fa-caret-up');

As in the css you can see the order of the classes. The one is last it just overrides the upper one in the order. So toggling a class fa-caret-up to an existing one is enough.

You can see the sample below:

$('[name="caret"]').click(function () {
  $(this).toggleClass('fa-caret-up');
});
body {
  font-family: Arial;
}

.accordion {
  border-top: 1px solid #c1c1c1;
}

.accordion dt {
  border: 1px solid #c1c1c1;
  border-top: 0px solid #c1c1c1;
  margin: 0px;
  padding: 10px 15px;
  display: block;
  cursor: pointer;
  overflow: hidden;
}

.accordion dt span {
  float: left;
  font-weight: normal;
  font-size: 17px;
}

.accordion dt .accordion_icon {
  float: right;
}

.accordion dt.active {
  background: #DBDBDB;
}

.accordion_content {
  margin: 0;
  padding: 15px;
  border-left: 1px solid #c1c1c1;
  border-right: 1px solid #c1c1c1;
  border-bottom: 1px solid #c1c1c1;
}
<link href="http://fontawesome.io/assets/font-awesome/css/font-awesome.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable" class="tablesorter table table-striped">
  <thead>
    <tr>
      <th width="75px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
      <th width="125px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
      <th width="550px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
      <th width="100px"><i name="caret" class="fa fa-caret-down fa-1x"></i></th>
      <th></th>
    </tr>
  </thead>
</table>
like image 44
Jai Avatar answered Mar 03 '26 07:03

Jai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!