otei arthur
otei arthur

Reputation: 1

How can I identify the view div section I have scrolled to?

I have a website with 4 divs that all have heights of 100vh that fill the entire view height and view width. But I can't seem to figure out the section of the div I have navigated to. Is there a way I can use

$(this).scrollTop()

to find out the view or div I am currently viewing? I know this question is quite confusing but if you understand what I am getting at, I truly need your help.

Upvotes: 0

Views: 268

Answers (2)

Ivan Demchenko
Ivan Demchenko

Reputation: 457

Basically, in your case, you have to know how much have you scrolled the page.

var scrolledY = window.scrollY || window.pageYOffset || document.documentElement.scrollTop;

After that, as long as your divs have height of 100vh it is the same as window.innerHeight. Therefore, you can calculate the index of div you scrolled to:

var divIdx = Math.floor(scrolledY / vh);

Now, all together: http://jsbin.com/qepodojoqa/edit?html,css,js,console,output

Upvotes: 2

Tomasz Rup
Tomasz Rup

Reputation: 859

You need to bind an event to scroll and check if you scrolled past a div's top offset.

$(document).scrollTop()

gives you your current top scroll, and

element.offsetTop

gives you the div's offset from the top (i.e, the distance between its top and the top of its parent node, body in this case).

Be aware that there are other ways to detect the top scroll, depending on your needs.

Upvotes: 0

Related Questions