MmD
MmD

Reputation: 2154

How to get position from top in pixel of an element?

I have one UL element which has 5 LI elements:

ul{
    width: 200px;
    height: 100%;
    padding: 0;
    margin: 0;
    overflow-y: auto;
    overflow-x: hidden;
    list-style: none;
    margin-left: 3px;
}

li{
    position: relative;
    height: 50px;
    width: 193px;
    left: 0;
    right: 0;
    margin: 10px 0;
    cursor: pointer;
}

I'd like to get the top pixel value for every LI from the UL top, but when I use this code:

$('ul li').each(function(){
    console.log($(this).css('top'));
});

it just shows me this : 'auto', why?

Upvotes: 2

Views: 6354

Answers (2)

Ehtesham
Ehtesham

Reputation: 2985

use offset if you want to get position relative to the document, use position to get position relative to the container element.

$('ul li').each(function() {
   var position = $(this).position();    // to get top value relative to container
   position = $(this).offset();          // to get position top relative to document
});

Upvotes: 1

rAjA
rAjA

Reputation: 919

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

$('ul li').each(function(){
   var position = $(this).position();

   console.log(position.top);
   console.log(position.left);
});

Upvotes: 3

Related Questions