Display only closest list elements
Asked Answered
P

3

6

Here is an example of what I have already

The main functionality works, but now I need to make the controller list smaller, so that it fits better to the screen, as it's fixed positioned.

So, I think it should show next three list-items from active item and 2 previous ones.

Something like this would work, but I think there should be shorter and more convinient way:

//Display closest items
$('#historyController li.active').prevAll('li:not(.first)').hide().slice(0,2).show();
$('#historyController li.active').nextAll('li:not(.last)').hide().slice(0,3).show();

Any tips for re-factoring current code for better performance would be helpful as well.

Palomo answered 9/1, 2013 at 9:10 Comment(2)
Something like this would work, but I think there should be shorter and more convinient way or any tips for re-factoring current code for better performance would be helpful as well If nothing is broken and your code works but you are simply looking for an alternative or better approach, this question might be better of on Stackexchange - Code ReviewCarryingon
Not sure if I entirely understand, but does the 'closest' method help you here: api.jquery.com/closestHoliness
R
0
<ul>
   <li>list item 1</li>
   <li>list item 2</li>
   <li class="third-item">list item 3</li>
   <li>list item 4</li>
   <li>list item 5</li>
</ul>

$('li.third-item').next().css('background-color', 'red');

Link for the documentation next()

This all items you can use for tree-traversal

Robbierobbin answered 13/1, 2013 at 8:35 Comment(0)
C
0

Use the following jQuery function.

<ul id="one" class="level-1">
<li class="item-i">I</li>
<li id="ii" class="item-ii">II
<ul class="level-2">
<li class="item-a">A</li>
<li class="item-b">B
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
</li>
<li class="item-c">C</li>
</ul>
</li>
<li class="item-iii">III</li>
</ul>

Jquery function is..

$('li.item-a').closest('ul').css('background-color', 'red');
Colossians answered 28/2, 2013 at 10:58 Comment(1)
This doesn't appear to be what Algeron is looking for. Please read questions carefully before posting answers.Pocketbook
S
0

You could try using .end(), in order to save on traversing:

$('#historyController li.active').prevAll('li:not(.first)').hide().slice(0,2).show().end().end().nextAll('li:not(.last)').hide().slice(0,3).show();
Scrubland answered 21/5, 2013 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.