Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count number of elements between "this" and "that" element

Tags:

jquery

I'm trying to know how "far" away a clicked element in the DOM is to a certain other element.

<li>item1</li>
<li>item2</li>
<li class="active">item3</li>
<li>item4</li>
<li>item5</li>
<li>item6</li>
<li>item7</li>

So when a user clicks an element it should return the distance to the active element: So item1: return -2, item4: return 1, item6: return 3, and so on.

like image 913
peirix Avatar asked Sep 07 '11 11:09

peirix


2 Answers

I believe you could do it the index() method...

Something like this:

var value = $('li').index() - $('li.active').index();
like image 139
Daniel A. White Avatar answered Oct 04 '22 03:10

Daniel A. White


Here you go:

$( ul ).delegate( 'li', 'click', function () {
    var idx1 = $( this ).index(),
        idx2 = $( this ).siblings().andSelf().filter( '.active' ).index();

    var distance = idx1 - idx2;

    // do stuff with distance
});

Live demo: http://jsfiddle.net/aeEBP/

like image 43
Šime Vidas Avatar answered Oct 04 '22 02:10

Šime Vidas