0

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.

Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107
  • 1
    Are you trying to have 4 different " pages " as divs? in that case put an id on each of the divs and show / hide the others when displaying one of them – MattiasH Mar 14 '17 at 10:03
  • You can take a look at how some libraries with a similar behavior do it. Take a look at [fullPage.js](http://alvarotrigo.com/fullPage/) and its [source code](https://github.com/alvarotrigo/fullPage.js/blob/master/jquery.fullPage.js#L954). – Alvaro Mar 29 '17 at 16:17

2 Answers2

2

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

Ivan Demchenko
  • 457
  • 3
  • 13
0

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.

Community
  • 1
  • 1
Tomasz Rup
  • 829
  • 1
  • 6
  • 13