Zach Russell
Zach Russell

Reputation: 1130

How to trigger a JavaScript function when the scroll bar reaches a certain percentage of the page height

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?

Upvotes: 2

Views: 2947

Answers (2)

tklg
tklg

Reputation: 2642

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>

Upvotes: 4

Fady Sadek
Fady Sadek

Reputation: 1140

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?

Upvotes: 2

Related Questions