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?
Using
.prevAll()and.nextAll()you can reduce all of your code in the question down to this:.prevAll()gets all previous siblings, and.nextAll()gets all following siblings, you can do what you want to each set.