views:

25

answers:

2

I need to select a specific grange of jquery elements based on there index using :eq() (or something else if you have a better solution)

my html structure is the following:

<ul>
  <li>slide0</li>
  <li>slide1</li>
  <li>slide2</li>
  <li>slide3</li>
  <li>slide4</li>
</ul>

When the user hovers slides over the slide2 i need to select li:eq(0), li:eq(1) and li:eq(3), li:eq(4) separatly, because they have a different animation.

This is my solution, but this feels a little messy...

var $slides, theOthers, slidesTotal;
$slides = $('ul > li');
slidesTotal = $slides.length;
theOthers = function(slideIndex ,slidesTotal){
   var before = [], after = [], i=0;
   while (i<=slideIndex - 1){
       before[i] = ":eq(" + i + ")"
       i++
   };
   while (i <= slidesTotal) {
       after[i] = ":eq(" + i + ")"
       i++
   };
   return [ before.join(",") , after.join(",") ]
}

$slides.mouseenter(function(){
   var groups, slideIndex, $that = $(this);
   slideIndex = $that.index();
   groups = theOthers(slideIndex, slidesTotal);
   $slides.filter(groups[0]).dosomething();
   $slides.filter(groups[1]).dosomethingelse()
})

is there a more simple way to do this with jQuery?

+5  A: 

Using .prevAll() and .nextAll() you can reduce all of your code in the question down to this:

$('ul > li').mouseenter(function() {
   $(this).prevAll().dosomething();
   $(this).nextAll().dosomethingelse();
});

.prevAll() gets all previous siblings, and .nextAll() gets all following siblings, you can do what you want to each set.

Nick Craver
this is exactly what i was looking for thank you
meo
@meo - Welcome :)
Nick Craver
A: 
jQuery('someElm ~ .someClass')-- 

matches all elements .someClass preceded by any siblings seomeElm
Praveen Prasad
how whould you apply this on my example?
meo
nick's answer: i think will solve ur problem.
Praveen Prasad
i know, but i wonder how yours fits to my question.
meo