Get the position of a clicked element with jquery?

I want to scroll to get the item in the view when it clicked, however I cannot get the top position when clicked:

Here is what I'm trying to do 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, it is now important which element to click. How can I do it right?

+4
source share
2 answers

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

Offset

+8
source
 scrollTop: $("#elementtoScrollToID").offset().top 
0
source

Source: https://habr.com/ru/post/1498960/


All Articles