Hafiz Temuri
Hafiz Temuri

Reputation: 4142

Slide and Toggle classes of font awesome jQuery

I am in a process of learning jQuery. There are many things I still don't understand. Here, I am trying to slide toggle the classes of font awesome. Not sure how can I achieve that. This is what I have so far.

$(function() {
    $("#nav").click(function(){
        $("#naver").slideToggle(function(){
            $("#nav i").removeClass("fa-bars").addClass("fa-eye");
        }, function(
            $("#nav i").removeClass("fa-eye").addClass("fa-bars");
        ));
    });
});

html,

<div id="nav">
    <i class="fa fa-bars fa-2x" aria-hidden="true"></i>
</div>

<ul id="naver">
    <a href="#"><li>Home</li></a>
    <a href="#"><li>About</li></a>
    <a href="#"><li>Contact</li></a>
</ul>

Upvotes: 2

Views: 268

Answers (2)

zer00ne
zer00ne

Reputation: 44088

You don't really need another callback function for slideToggle(), and using toggleClass() will save you a few lines of code as well. In general, if we have only one event (i.e. click), we can tie in all of the functions associated with that one event within that event.

SNIPPET

$(function() {
  $("#nav").click(function() {
    $("#naver").slideToggle();
    $("#nav i").toggleClass('fa-bars fa-eye');
  });
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/fontawesome/4.7.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="nav">
  <i class="fa fa-bars fa-2x" aria-hidden="true"></i>
</div>

<ul id="naver">
  <a href="#">
    <li>Home</li>
  </a>
  <a href="#">
    <li>About</li>
  </a>
  <a href="#">
    <li>Contact</li>
  </a>
</ul>

Upvotes: 1

rorymorris89
rorymorris89

Reputation: 1189

You had a slight typo in your second callback function, although you can't use multiple callback functions as you've tried with slideToggle. I've amended your code, preview here: https://jsfiddle.net/4xu16oqn/1/

JS

$(function() {
    $("#nav").click(function(){
        $("#naver").slideToggle(250);
        $("#nav i").toggleClass("fa-bars").toggleClass("fa-eye");
    });
});

HTML

<div id="nav">
    <i class="fa fa-bars fa-2x" aria-hidden="true"></i>
</div>

<ul id="naver">
    <a href="#"><li>Home</li></a>
    <a href="#"><li>About</li></a>
    <a href="#"><li>Contact</li></a>
</ul>

CSS

#naver{ display:none; }

Upvotes: 2

Related Questions