Triggering a scroll event

Michael Carneal
2 min readAug 19, 2019

In many websites today it is common practice to have some sort of event take place at a certain scroll point within the window.

Lets say that on your site you want to set an alert to happen when the user scrolls to the bottom of your screen.

Want you ll want to do is write some JavaScript magic that can calculate the height of your screen and your document and then trigger the event.

Below is a code sample that will do just that, we will than break down what is happening.

$(window).scroll(()=> {
if($(window).scrollTop() + $(window).height() > $(document).height() -100 ) {
$(window).unbind('scroll');
alert("near bottom!");}
});

What we are doing is creating a function that will bind to the window. Inside this we use (window).scrollTop(), (window).height(), and (document).height().

(window).scrollTop() will tell you the current scroll position your browser is currently at.

(window).height() will calculate the height of your browsers window.

(document).height() will tell you how tall the page you are currently viewing is.

So inside our function we want to create a conditional statement that will add the scroll position plus the window height, and if those to combine are larger than the document plus 100 pixels, we will then create an alert telling our users we are close to the bottom of the page.

The 100 pixels is completely optional and is just used as an arbitrary number. In some cases you may want the conditional to be scroll position plus window height to be greater than 10 percent of the document. That is completely up to you as the developer.

In many case we would not want to use an alert and instead trigger a modal to appear. Which we will go through in an upcoming post.

Happy coding :-)

--

--