Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Infinite scrolling - via .onscroll (execute code on scrolling) #25

Open
tdoran opened this issue Mar 30, 2018 · 1 comment
Open

Infinite scrolling - via .onscroll (execute code on scrolling) #25

tdoran opened this issue Mar 30, 2018 · 1 comment

Comments

@tdoran
Copy link
Contributor

tdoran commented Mar 30, 2018

Using window.onscroll = function(){ } you can execute code as the user scrolls your page.

The code below will track the height of the page using document.documentElement.offsetHeight and compare it to the height scrolled with document.documentElement.scrollTop + the height of the window window.innerHeight.

Then using if (offset >= (height * 0.9)) you can execute code when the amount scrolled + height of window is equal to 90% of the height of the page (i.e. the user has almost reached the bottom).

window.onscroll = function() {
  var offset = document.documentElement.scrollTop + window.innerHeight;
  var height = document.documentElement.offsetHeight;
  

  console.log('offset = ' + offset);
  console.log('height = ' + height);

  if (offset >= (height * 0.9)) {
    console.log('At 90%');
    height = document.documentElement.offsetHeight;
  }
};

I haven't got it working perfectly at this stage - The tricky part is making sure the code will only be executed once when it reaches 90% - so comments/corrections welcome.

@jennah2121
Copy link
Contributor

I think the intersectionObserver also allows you to do this but in an asynchronous way which is better for performance (not 100% sure on this). You also don't have to do any calculations :)

I found it relatively easy to get working. However, its not fully supported yet. For anyone who's interested I found the following links helpful:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants