Search code examples
javascriptjqueryslidetoggle

Remove Class when current toggle is clicked


The title is a bit of a tongue twister. A brief description of the fiddle, is that it's a toggle style accordion where the toggle state changes color when one of the divs is toggled. I've got it working to where if another div is toggled it will close that previous div and open the new div while changing the toggle state.

The issue I am running into is if a user wants to close the current toggle without clicking a different div it will close the current toggle but not change the toggle state back to it's original state. I am currently using this and have tried multiple things including if the container 'is: visible' or hasClass then to remove the toggle class, but nothing seems to work. I've also tried a different slideToggle function, but of course that applied it to the toggled element I've found.

Fiddle: http://jsfiddle.net/NFTFw/1256/

What I am trying to do?

I want the current toggle class to change back to its original state if the user clicks the current toggled div or clicks another div. So essentially I want the user to have either option.

CODE:

  $(document).ready(function () {
      $('.column').each(function (index) {
          $(this).delay(750 * index).fadeIn(1500);
      });
      $('.column').hide();
      $('.body').hide();
      $('.column').each(function () {
          var $toggle = $(this);
          $('.toggle', $toggle).click(function () {
              $(".toggle").removeClass("toggle-d");
              $(this).addClass('toggle-d');
              $body = $('.body', $toggle);
              $body.slideToggle();
              $('.body').not($body).hide();
          });
      });
  });

Solution

  • Check to see if the thing that you're clicking already has the class. If so, remove it, if not, add it. I suspect the problem you were having with hasClass() is that you were attempting to check the wrong this.

    Oooh I did a bad thing and didn't remove the class when a new div was clicked. I've fixed that and updated the jsfiddle

    jsfiddle

    js:

    $(document).ready(function () {
          $('.column').each(function (index) {
              $(this).delay(750 * index).fadeIn(1500);
          });
          $('.column').hide();
          var width = $(window).width();
          if (width <= 600) {   
          $('.body').hide();
          $('.column').each(function () {
              var $toggle = $(this);
              $('.toggle', $toggle).click(function () {
                  if($(this).hasClass('toggle-d')){
                    $(this).removeClass("toggle-d");
                  }
                  else{
                    $('.toggle').removeClass('toggle-d');
                    $(this).addClass('toggle-d');
                  }
                  $body = $('.body', $toggle);
                  $body.slideToggle();
                  $('.body').not($body).hide();
              });
          });
          }
      });