Skip to content
Advertisement

Toggle multiple divs with multiple buttons using animate.css – jQuery

I have three different buttons with three different divs that each toggle an applicable div in same place. Trying to do 2 things.

  1. Add class on .app-icon button when relative .app-div is showing so that I can add background color when active.
  2. Add an animate.css effect when toggling same .app-div open and closed so that when the div disappears it slides down, rather than just abruptly disappearing.

HTML:

<a href="#" class="app-icon"><i class="fa fa-calculator" aria-hidden="true"></i></a>
<a href="#" class="app-icon"><i class="fa fa-sun-o" aria-hidden="true"></i></a>
<a href="#" class="app-icon"><i class="fa fa-rss" aria-hidden="true"></i></a>

<div class="app-div">
content div 1
</div>

<div class="app-div">
content div 2
</div>

<div class="app-div">
content div 3
</div>

jQuery:

$('.app-icon').click(function() {
  var index = $(this).index();
  $('.app-div').eq(index).toggle().siblings('.app-div').hide();
});

//animate.css effect
$('.app-div').addClass('animated fadeInUp');

Here’s what I have so far: https://jsfiddle.net/frshjb373/a5osx7y6/3/

Advertisement

Answer

One option is to handle an if statement checking if the icon clicked is actually active like this:

$('.app-icon').click(function() {
  var index = $(this).index();
  if($(this).hasClass('active')) {
     $(this).removeClass('active');
     $('.app-div').eq(index).addClass('fadeOutDown')
  } else {
     $('.app-icon').removeClass('active');
     $(this).addClass('active')
     $('.app-div').hide().eq(index).show().removeClass('fadeOutDown')
  }
});

Updated Demo

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement