41

I am using font awesome 'plus' icon on expandable categories list items. When they are in expanded state i want to show a 'minus' sign'

HTML

<ul id="category-tabs">
    <li><a href="javascript:void"><i class="fa fa-fw"></i>Category 1</a>
        <ul>
            <li><a href="javascript:void">item 1</a></li>
            <li><a href="javascript:void">item 2</a></li>
            <li><a href="javascript:void">item 3</a></li>
        </ul>
    </li>
</ul>

Jquery

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
});

enter image description here

Orahmax
  • 2,301
  • 4
  • 22
  • 32

6 Answers6

92

You can toggle the class of the i element within the clicked anchor like

<i class="fa fa-plus-circle"></i>

then

$('#category-tabs li a').click(function(){
    $(this).next('ul').slideToggle('500');
    $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});

See working example:

$('#category-tabs li a').click(function() {
  $(this).next('ul').slideToggle('500');
  $(this).find('i').toggleClass('fa-plus-circle fa-minus-circle')
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<ul id="category-tabs">
  <li>
    <a href="javascript:void">
      <i class="fa fa-plus-circle"></i> Category 1
    </a>
    <ul>
      <li><a href="javascript:void">item 1</a></li>
      <li><a href="javascript:void">item 2</a></li>
      <li><a href="javascript:void">item 3</a></li>
    </ul>
  </li>
</ul>
lokarkristina
  • 305
  • 4
  • 9
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • The changes are working with href remain same, however say for MVC if one call view to display the content the menu icon is not changes( or rather it change and refresh back to original) . How to make it persist? The example that worked
  • Check or Uncheck
  • and the below that didn't worked
  • Check or Uncheck
  • – AKS Jun 19 '15 at 10:22
  • 3
    4 years later and still useful :-) just to note that if you're using the svg graphics, the 'i' element will be replaced with an 'svg' so the toggleClass needs to be applied to $(this).find('svg') instead of 'i' – Iosu S. Jan 09 '18 at 08:13