Galili Omri
Galili Omri

Reputation: 310

Side Bar - close and open the filter list

I'm building a filter sidebar for my site, I want to be able to open and close the filter lists by pressing a btn.

jQuery('.parent > .children').parent().click(function() {
  jQuery(this).children('.children').slideToggle(200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>

My problem is that when I press the list it closes, I want it to remain open.

Upvotes: 2

Views: 489

Answers (2)

fen1x
fen1x

Reputation: 5880

You should give class to your button and target only this class:

$('.toggler').click(function() {
  $(this).siblings('.children').slideToggle(200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <span class="toggler">+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span class="toggler">+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span class="toggler">+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>

Upvotes: 4

ᔕᖺᘎᕊ
ᔕᖺᘎᕊ

Reputation: 3011

You need to check that the click isn't happening on the actual li.

Use event.target to do nothing if the click is directly on the li elements, so adding this to the click handler should do it:

if ($(e.target).is('li')) return;

jQuery('.parent > .children').parent().click(function(e) {
  if ($(e.target).is('li')) return;
  jQuery(this).children('.children').slideToggle(200);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
<div class="parent">
  <span>+</span>
  <ul class="children">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>

Upvotes: 2

Related Questions