Jeff
Jeff

Reputation: 4003

How to find paragraph closest to the top of the viewer

I'm trying use javascript to identify the paragraph element that is closest to the top of the viewing area at the time that the function was fired.

I tried to use: http://gilmoreorless.github.io/jquery-nearest/

with the following code:

var $paragraphs = $('p.plaoulparagraph');
console.log($paragraphs.nearest({y: 0, x: 0}));

But this always gives me the first paragraph no matter what is visible in the viewport.

I think the reason this is not working is that according to the documentation the coordinates refer to the page, not the viewing area.

pointObject is an object with x and y (numeric) properties that define a point on the page (relative to the top left corner of the page, not the screen).

Any other ideas?

Upvotes: 0

Views: 65

Answers (1)

charlietfl
charlietfl

Reputation: 171690

I've never used this plugin but the top of viewport and $(window).scrollTop() are the same so try:

$paragraphs.nearest({y: $(window).scrollTop(), x: 0});

Upvotes: 1

Related Questions