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.
I believe you could do it the index()
method...
Something like this:
var value = $('li').index() - $('li.active').index();
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With