Toggle css class in a Nav toggle, using Jquery

Asked

Viewed 301 times

2

I’m making a menu with a toggle using Jquery. The menu is working perfectly.

I’m using a class from Font Awesome to show the icon on the button to activate the toggle. I want to change the class fa-chevron-circle-down for fa-chevron-circle-up when the toggle is activated, and return the class to initial when the toggle is disabled.

Follows the code

HTML:

<nav class="nav-menu">
    <ul class="nav-list shadow">
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
    <button class="nav-toogle shadow"><i class="fa fa-chevron-circle-down fa-3x" alt="Menu Arrow"></i>
    </button>
</nav>

jQuery:

$(document).ready(function(){
    $('.nav-toogle').click(function(){
        $('.nav-list').slideToggle('slow');    
    }); 
});

1 answer

1


You can use the .toggleClass() and pass the two classes separated by spaces. Once the element that receives the event click is the button you must select the element i. You can do that with .find('i').

The code would look like this:

$(document).ready(function(){
    $('.nav-toogle').click(function(){
        $(this).find('i').toggleClass('fa-chevron-circle-down fa-chevron-circle-up');
        $('.nav-list').slideToggle('slow');    
    }); 
});

Example: http://jsfiddle.net/6kv3cf9c/

  • 1

    Thank you, Sergio. Solved my problem. The menu is working perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.