Search code examples
javascriptjqueryslidetoggleslidedown

One click event with multiple triggers to make content slide up and down


I am here again for another question I need help in but can't seem to find a solution to. I have this feature utilizing slideDown() and slideUp(), which you can view here.

The issue here is I've tried slideToggle() but I'm looking to collapse one content area when another trigger link is clicked and slideToggle() keeps it open unless you click on the same trigger link again to close it.

var panel = $('.panel').hide();

$('.toggle').click(function(event) {
  event.preventDefault();
  var loc = this.id; //this grabs the name of the location  

  if ($('.panel').hasClass('clicked')) {
    $('.panel.clicked').removeClass('clicked');
    $('.panel').slideUp();
  }

  $('.panel.' + loc).addClass('clicked');
  $('.panel.' + loc).slideDown();
});

Currently the code above works but if you were to click on TMC and click on TMC again to close it, it slides up and slides down again. SlideToggle will just open all of them.

Thanks!


Solution

  • You need to check to see if the panel was previously open before sliding it down. You can do this by selecting the panel corresponding to the clicked .toggle element and checking whether it has a class of clicked. Aside from that, I simplified your code a little as well.

    Updated Example

    $('.toggle').click(function(event) {
      var id = this.id,
          wasOpen = $(this).closest('.expand').next('.panel').hasClass('clicked');
    
      event.preventDefault();
      $('.panel').removeClass('clicked').slideUp();
    
      if (!wasOpen) {
        $('.panel.' + id).addClass('clicked').slideDown();
      }
    });