user3544484
user3544484

Reputation: 851

jQuery toggleclass 2 divs - open one & close the other

I have 2 div's that I open with toggleClass, as below:

<!-- links to open div's -->
<div class="sort-filter">
  <div class="sort">
    <a href="#" class="sort"><em class="fa fa-sort"></em> SORT</a>
  </div>
  <div class="filter">
    <a href="#" class="filter"><em class="fa fa-filter"></em> FILTER</a>
  </div>
</div>

<!-- divs to toggle open/close -->
<div class="search-options clearfix" style="display: none;">
  content options here
</div>
<div class="search-filters clearfix" style="display: none;">
  content filters here
</div>

I use the the following jQuery to toggle the div's:

<script type="text/javascript">
$(function ($) {
    var search_options = $('.search-options');
    $('a.sort').click(function () {
        $(this).toggleClass('show');
        search_options.slideToggle(400);
        if ( !$(this).hasClass('show') ) {
            $('a.filter').removeClass('show'); // hide the other one
        }
        return false;
    });
    var search_filters = $('.search-filters');
    $('a.filter').click(function () {
        $(this).toggleClass('show');
        search_filters.slideToggle(400);
        if ( !$(this).hasClass('show') ) {
            $('a.sort').removeClass('show'); // hide the other one
        }
        return false;   
     });
});
</script>

But my logic is screwed.

I want one link to close the other div if open & vise-versa.

Any idea's?

jsfiddle here...

Upvotes: 0

Views: 1371

Answers (1)

James Waddington
James Waddington

Reputation: 2905

Your current code removes the show flag from the toggle, but it doesn't do anything to actually hide the content area. You can add a slideUp() to do that:

$(function ($) {
    var search_options = $('.search-options');
    $('a.sort').click(function () {
        $(this).toggleClass('show');
        search_options.slideToggle(400);
        if ( $(this).hasClass('show') ) {
            $('a.filter').removeClass('show'); // mark the other as hidden
            search_filters.slideUp(400); // hide the other one
        }
        return false;
    });
    var search_filters = $('.search-filters');
    $('a.filter').click(function () {
        $(this).toggleClass('show');
        search_filters.slideToggle(400);
        if ( $(this).hasClass('show') ) {
            $('a.sort').removeClass('show'); // mark the other as hidden
            search_options.slideUp(400); // hide the other one
        }
        return false;   
     });
});

Here's a fiddle: http://jsfiddle.net/yj9f5qh8/

Upvotes: 1

Related Questions