Scott Eldo
Scott Eldo

Reputation: 473

Fade toggleClass using Font Awesome switching

I have a menu toggle that when clicked, changes the Font Awesome icon class from a hamburger to a cross. I want some sort of animation, a simple fade will do of the toggleClass. Because its switching the class the fade doesn't work like it would do if I were just adding the class as you'd assume below.

$( ".menu-toggle" ).click(function() {
    $(this).find('i').toggleClass('fa-bars fa-times', 1000);
});

How can I add a simple fade to the below code?

$( ".menu-toggle" ).click(function() {
    $(this).find('i').toggleClass('fa-bars fa-times');
});

Upvotes: 1

Views: 1919

Answers (1)

PaulELI
PaulELI

Reputation: 444

Try this out? It doesn't use font awesome, but gives you the same effect using CSS.

Html:

<div class="hamburger">
  <span class="line"></span>
  <span class="line"></span>
  <span class="line"></span>
</div>

CSS

.hamburger {
  width: 30px;
  height: 20px;
  position: relative;
  margin: auto;
}
.hamburger .line {
  display: block;
  width: 100%;
  height: 2px;
  background: #000;
  position: absolute;
  transition: all 200ms;
}
.hamburger .line:nth-child(1) {
  top: 0;
}
.hamburger .line:nth-child(2) {
  top: 50%;
  transform: translateY(-50%);
}
.hamburger .line:nth-child(3) {
  bottom: 0;
}
.hamburger.close .line:nth-child(1), .hamburger.close .line:nth-child(2)          {
  top: 0;
  transform: translateY(9px) rotate(45deg);
}
.hamburger.close .line:nth-child(3) {
  transform: translateY(-9px) rotate(-45deg);
}

body {
  margin: 20px;
}

JS

$('.hamburger').click(function(e) {
  $(this).toggleClass('close');
});

http://codepen.io/peiche/pen/bfchi

Upvotes: 2

Related Questions