giantqtipz giantqtipz - 2 months ago 15
jQuery Question

jquery, combining .not and .eq?

Yesterday I posted a problem with targeting 2 the same index within 2 separate unordered lists.

basically, items in unordered list #2 are hidden -- and when you click on an item in unordered list #1, an item with the same index in unordered list #2 will show up.

<ul class="list1">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ul>
<ul class="list2">
<li class="hide">item 1</li>
<li class="hide">item 2</li>
<li class="hide">item 3</li>
<li class="hide">item 4</li>
</ul>

.hide { display: none; }
.active { display: block; }


The solution based on the responses is:

$('.list1').on('click', 'li', function() {
$('.list2 li').eq($(this).index()).addClass('active');
});


and this works great!

Now, I'm trying to make it so that when one line item shows up, the rest disappears.

I read that you can do this with the
.not()
method, but I'm struggling with binding it with the
.eq()
method.

if I have the two codes below on top of each other, it will only remove but not add.

$('.list2 li').eq($(this).index()).addClass('active');
$('.list2 li').not().eq($(this).index()).addClass('active');


I figured I would have to put the
.eq()
inside the
.not()
method, but not sure how. Also I tried using if statements but that wasn't successful either..

would appreciate any input you can provide. Thanks!

Answer

Why not just remove the active on all li items and only add it to the relevant li?

$('.list1').on('click', 'li', function() {    
  $('.list2 li')
    .removeClass('active')
    .eq($(this).index()).toggleClass('active');
});
.hide { display: none; }
.active { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list1">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
</ul>
<ul class="list2">
  <li class="hide">item 1</li>
  <li class="hide">item 2</li>
  <li class="hide">item 3</li>
  <li class="hide">item 4</li>
</ul>

If you really want to use the not function you can use it this way:

$('.list1').on('click', 'li', function() {
  relevantLi = $('.list2 li').eq($(this).index())
  $('.list2 li').not(relevantLi).removeClass('active')
  relevantLi.addClass('active')
});
.hide { display: none; }
.active { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list1">
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
</ul>
<ul class="list2">
  <li class="hide">item 1</li>
  <li class="hide">item 2</li>
  <li class="hide">item 3</li>
  <li class="hide">item 4</li>
</ul>

Comments