Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get position of clicked element with jquery?

Tags:

jquery

scroll

I want to scroll to get an item into view when it's clicked, however I cannot manage to get it's top position on click:

This is what I'm trying right now:

    $( "section" ).click(function(e) {
        console.log("thing top: "+$(this).position().top);
        //$('html,body').animate({ scrollTop: 0 }, 'slow');
        //return false; 
    });

However I always get the same top position, now matter what element is clicked. How can I do this right?

like image 774
lisovaccaro Avatar asked Aug 26 '13 13:08

lisovaccaro


People also ask

How to get clicked element position in jQuery?

The . position() method allows us to retrieve the current position of an element (specifically its margin box) relative to the offset parent (specifically its padding box, which excludes margins and borders). Contrast this with . offset() , which retrieves the current position relative to the document.

How do you find the position of a clicked element?

To get the position of all the elements between what you clicked on and the document, you have the getPosition function. This function provides you with the additional pieces of information needed to make your existing calculations involving clientX and clientY complete.

How do you find XY coordinates of a div?

The position of (X, Y) means the co-ordinate of an element at the top-left point in a document. X represent the horizontal position and Y represent the vertical position. Use element. getBoundingClientRect() property to get the position of an element.

What is the difference between position and offset in jQuery?

Although both methods have some similarities, but the jQuery offset() method is different from the jQuery position() method. The offset() method retrieves the current position relative to the document, whereas the position() method retrieves the current position of an element relative to the parent element.


1 Answers

Try $(this).offset().top as it gets the position relative to the document rather than the parent

Offset

like image 108
DGS Avatar answered Oct 10 '22 18:10

DGS