adr
adr

Reputation: 362

Grabbing a reference to the element closest to scrollTop

I'm wondering how to grab a reference to whatever DOM node happens to be closest to document.body.scrollTop at any given time.

Let's say I had 10 paragraphs inside a div, and the scrollTop at 400px is on p child 5.

I want to store that information and return the user to that paragraph when they come back. Of course I could simply reset the scrollTop to a given value, but if the browser is resized or the orientation is changed, this isn't a reliable method (and media queries might alter the size of elements).

However, if I could store the value of the node at the top, I can use .scrollIntoView() and be sure the user is in the correct location.

Any thoughts?

Thank you.

Upvotes: 1

Views: 1782

Answers (1)

Stephen Thomas
Stephen Thomas

Reputation: 14053

Easy enough if you know the document structure. To continue your example:

// div is the parent <div> element
var el, top, min = Number.MAX_VALUE, els = div.getElementByTagName('p');
for (var i=0; i<els.length; i++) {
    top = Math.abs(els[i].getBoundingClientRect().top);
    if (top < min) {
        min = top;
        el = els[i];
    }
}

// el now holds the <p> whose top is closest to the top of the window

Upvotes: 2

Related Questions