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?
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.
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.
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.
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.
Try $(this).offset().top
as it gets the position relative to the document rather than the parent
Offset
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