Reputation: 167
I use this code to toggle a font awesome icon. The toggle is working but I want to give some animation there. But animation not working.
HTML:
<header>
<h4><i class="fa fa-bars" aria-hidden="true"></i></h4>
</header>
jQuery:
$('header h4').click(function() {
$("i", this).toggleClass("fa-bars fa-times", 1000);
});
Upvotes: 0
Views: 475
Reputation: 1497
I'm assuming you want a fade in/out effect on your icons.
$('header h4').click(function(e) {
//if the icon has the class fa-bars
if ($("i", this).hasClass('fa-bars')) {
//fade the icon element out
$("i", this).fadeOut('fast', function() {
// remove the element from the dom
$(this).remove();
});
// create the new element, append it to the dom, hide it immediately, then fade it in
$('<i class="fa fa-times"></i>').appendTo($(this)).hide().fadeIn('fast');
} else { //otherwise the icon has the other class (fa-times)
//fade the icon element out
$("i", this).fadeOut('fast', function() {
// remove the element from the dom
$(this).remove();
});
// create the new element, append it to the dom, hide it immediately, then fade it in
$('<i class="fa fa-bars"></i>').appendTo($(this)).hide().fadeIn('fast');
}
});
.fa-bars, .fa-times {
position: absolute;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<h4><i class="fa fa-bars" aria-hidden="true"></i></h4>
</header>
Upvotes: 1