2

I am looking for a solution written in plain JavaScript that fires a JS function at a certain percentage of a page scroll (say 80%). I am looking to accomplish something similar to what Waypoints does, without 750 lines of code or using jQuery.

I'm assuming I would figure determine the height of the window then trigger the callback once the scroll point is greater than 80% of the height.

The other requirements here are that I only want it to trigger once. The other concern I have is potential performance issues of constantly polling for the scroll percentage. Is this a valid concern?

Fady Sadek
  • 1,091
  • 1
  • 13
  • 22
Zach Russell
  • 1,060
  • 2
  • 13
  • 27

2 Answers2

3

A way that will check the page scroll once every 500ms while scrolling, and will only run once:

var throttledListener = throttle(scrollListener, 500);
window.addEventListener('scroll', throttledListener);

function throttle(func, delay) { // allows [func] to run once every [delay] ms
    var func = func.bind(func),
        last = Date.now();
    return function() {
        if (Date.now() - last > delay) {
            func();
            last = Date.now();
        }
    }
}
function scrollListener() {
    console.log('scrolled');
    var threshold = document.body.clientHeight * 0.6;
    if (window.pageYOffset >= threshold) {
        alert('user scrolled to threshold; listener removed');
        window.removeEventListener('scroll', throttledListener);
    }
}
<div style="height:2000px;width:100%">tall div</div>
tklg
  • 2,572
  • 2
  • 19
  • 24
2

You can use onscroll

function trigerScroll(ev){ if(window.pageYOffset>400)alert('User has scrolled at least 400 px!'); } window.onscroll=trigerScroll ;

Edit:

you can get the document height like this

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );

source : How to get height of entire document with JavaScript?

Community
  • 1
  • 1
Fady Sadek
  • 1,091
  • 1
  • 13
  • 22
  • Your snippet isn't working for me. [Here](http://codepen.io/protechig/pen/VPbbPR?editors=1111) is a working codepen of what i'm working with. I tried to have it just `console.log()` something on scroll and it doesn't look like it's triggering. – Zach Russell Jan 22 '17 at 01:54
  • `window.onscroll=trigerScroll()` should be `window.onscroll=trigerScroll` – tklg Jan 22 '17 at 02:32