Jasper
Jasper

Reputation: 5238

Get position of the li jQuery

We have a simple ul

<ul><li>text</li><li>text</li><li>text</li><li>text</li></div>

How do take a position of the <li>, from the top and left corner of the <ul>?

li is display: inline, ul has text-align: center. Text inside ul can be divided to several lines.

Upvotes: 4

Views: 7881

Answers (2)

thirtydot
thirtydot

Reputation: 228152

You should use .position(). You can select a specific li using :nth-child.

You'll also need to set position: relative on the ul.

For example, to obtain the position of the second li relative to the ul:

http://jsfiddle.net/thirtydot/TgXvp/

var position = $('li:nth-child(2)').position();

alert(position.top);
alert(position.left);

Upvotes: 7

tonycoupland
tonycoupland

Reputation: 4247

Using jQuery's position method you can get the coordinates of the ul and lis and then subtract them to get the relative position.

As in:

var vertDiff = $('ul li:first').position().top - $('ul').position().top;

Upvotes: 1

Related Questions