How To Handle Scroll Events In JavaScript
Jennifer Eze
Posted on December 6, 2022
Introduction
You know sometimes, it's really useful to listen to scroll events to find out about the user's scroll position as they scroll up and down the web or even scroll within an element in a webpage.
Let’s take pinterest.com as an example; you will notice that as the user scrolls down the bottom of the page, more images keep loading.
In this case, we can say, we use scroll events for infinite scrolling. we can also use the scroll bar to toggle the class of a nav bar to hide and unhide it.
In this article, we are gonna learn about JavaScript scroll events.
A Scroll Event is what?
A scroll event in JavaScript causes a scrollbar position to change, either vertically or horizontally. A JavaScript event listener or JavaScript event handler can be used to hear it.
For reading scroll (desktop) or touch (mobile) events, the scroll event handler is an NPM package, and each event is given a callback.
Since "scroll" is a JavaScript event, we can add an event listener to any Document Object Model element to receive scroll events.
Events that occur as a result of scroll events.
a. Scroll events cause animations to start playing: some websites with animations get prettier as you scroll down the page. The animation plays more smoothly as you use the scroll bar to advance. such as webflow.com
b. Toggling a class: If you scroll a little through the viewport on numerous websites, such as pitchefork.com, you will frequently notice this. If you look at the navbar, you'll see that the concealed navigation initially becomes visible.
Therefore, to conceal and reveal it in this situation, use the toggle case of a scroll event.
How to hear scroll events
Regarding Windows objects
a. On Windows objects:
There are two ways we can listen for it; To listen to a scroll event, you first have to scroll up and down your browser.
like in the image above, you won’t find a scroll bar. but to get one. make a <P> tag or a paragraph tag, and put some dormie text inside.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<P>Lorem ipsum dolor sit amet consectetur adipisicing elit. Aspernatur amet quod explicabo nihil numquam sunt officiis corrupti? Temporibus vero corporis omnis dolorem aspernatur, nihil eos eaque maxime deleniti molestiae vitae aperiam ut laboriosam dolore quo est architecto nemo nulla dolorum exercitationem neque quos! Corrupti ad dignissimos tenetur aspernatur provident! Quidem consectetur sapiente laudantium dignissimos similique in, quibusdam quod vitae dolorem explicabo necessitatibus eveniet nemo vel dolore accusamus ducimus nulla fugiat maiores id! Nesciunt quaerat harum, labore, amet maxime, ratione ab nobis illum atque deleniti nemo expedita earum possimus culpa exercitationem porro architecto iste. Velit placeat tempore, odio eveniet earum iusto consequuntur quidem vel quis repellat perferendis commodi ea mollitia laborum tempora inventore at. Pariatur ipsum reprehenderit earum nobis! Recusandae, accusantium tempore quatibus maiores ducimus adipisci dolorem voluptas sint voluptatum voluptates libero, quod magnam explicabo rerum? Autem aliquid mollitia modi minima quasi, temporibus totam eum fugit eaque. Excepturi officiis ab deserunt est! Quaerat expedita harum iusto pariacepturi sapiente non dicta? Fuga totam quae
similique sapiente voluptas accusantium maxime nam omnis fugit ratione, blaasi omnis. Alias fuga hic eveniet, qui corporis nostrum, dicta maiores vel voluptatum quibusdam facilis modi saepe quo facere dolore magni ipsa excepturi assumenda ex et qus impedit esse sequi numquam officia? Earum autem pariatur, eos nihil excepturi officiis nulla officia quam velit neque, iste omnis quidem laborum modi ad quod placeat fugiat? Assumenda aliquid, aspernatur ipsam rerum illum cumque esse, excepturi eveniet sunt velit ea eum. Dolor error, id animi nihil eos, nemo vo!</P>
</body>
</html>
If you go back to the browser, you will see all those tags, which will now give us a scroll bar.
As you can see we have a scroll bar now and we can scroll up and down the page.
Here is the first way, that we can listen to scroll events;
METHOD 1: USING THE ONSCROLL PROPERTY
Because we frequently wish to track the full scrolling of the webpage up and down, it is very usual to listen to scroll events on the window object.
We now use the windows object to accomplish that. We have a property named on-scroll in my script.js. You can find out when the scroll event is being fired by assigning it to a function and then logging it to the console.
window.onscroll = () => {
console.log("white creativity")
}
You'll see that the number keeps rising as we scroll down the bar.
Be aware that the scroll event rapidly sets file-zealous times. If you want to perform complex event handling or a call-back function, the scroll event is one of the event kinds that can be difficult.
Debouncing, throttleing, and other methods are some of the ways these many items might be improved.
METHOD 2: USING addEventListener
Now, instead of windows. onscroll, it will be windows. addaEventListener. like this
window.addEventListener ("scroll",() => {
console.log("white creativity");
})
The first argument is the name of the event which is scroll, the second argument will be the event handler call-back function. which is the event function that is going to run when this event function is fired. finally console.log again.
The same thing occurs: the number keeps rising as you scroll the bar.
The addEventListener method is recommended for listening to events because
We can add several event handlers to the scroll events using the addEventListener function.
On windows objects, we have so far listened to scroll events. Now that it's on page elements, we can hear it.
watching for scroll events on the page's elements
We'll see that we are an example. Form a div. Put a paragraph tag inside of it.
Make a div and insert a paragraph element with some placeholder content within the div.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta HTTP-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<p>monkeys love bananaLorem ipsum dolor sit amet consectetur, adipisicing elit. Qui perferendis deleniti nisi, saepe debitis error laborum! Exercitationem porro tenetur architecto, officiis voluptates maxime. Dolorem commodi nobis sapiente deleniti quos eligendi. Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus, accusantium. Dicta necessitatibus delectus fugiat minima molestias. Enim dolorum eum eos, aliquid eius nihil placeat cumque reprehenderit nesciunt perferendis tenetur possimus. </p>
</div> </p>
</div>
<script src="script.js"></script>
</body>
</html>
style it a little bit in your CSS, like this
.container{
width: 500px;
height: 500px;
background-color: blue;
overflow: auto;
}
.container p{
height: 1000px;
width: 1000px;
font-size: 2rem;
margin: 0;
}
on script.js, write this code.
document.querySelector(".container")
.addEventListener("scroll", (a) =>{
console.log(a)
})
To target the container, we use the query selector and a div with a class of container.
Then we call adEventListener and pass in the scroll event and the event handler calls back function.
whenever we add an event listener, we have access to the event object itself. we can use whatever we want, but I just want to use the small letter “a”. finally to look at the event object; console.log(a).
scroll inside the container itself. Take a look at the console. you are going to see a whole lot of running object that was logged.
If you type that code into your browser console and scroll, you will see that you get undefined. The intriguing point is that we won't need scrollTop or scrollLeft while working with the windows object. Instead, we'll employ scrollY and scrollX.
You will see that you are obtaining numerical values in the console if you utilize scrollY and check the browser console.
document.querySelector(".container")
.addEventListener("scroll", (a) =>{
console.log(a.target.scrollTop)
})
if you write that code and go back to the console, you will notice that as we scroll down, the number of pixels increases.
Now if you want to see horizontally how much we have scrolled, you will see the left scroll property.
we wanna go back to our previous example when we looked at the scroll event on the window object.
window.addEventListener ("scroll",() => {
console.log(window.scrollTop);
})
if you write that code and scroll on your browser console, you will notice that you will get undefined. so the interesting thing is that when we are dealing with the windows object, we will not use scrollTop or scrollLeft. but rather we will use scrollY and scrollX.
if you use scrollY and look in the browser console you will notice that you will be getting numerical values in the console.
Conclusion
we have come to the end of this article. I hope you gained a whole lot on how to scroll events are handled in JavaScript. you can take out some time to try that. if you have questions, drop them in the comment section. And it will be attended to. Don’t forget to follow me and give a clap to this tutorial, expecting to see you in the next one…
About the Author
I am Jenifer Eze, an enthusiastic developer with a passion for JavaScript, Bootstrap, PHP, HTML & CSS.
I work as a freelancer, building websites for clients, and love writing technical tutorials to teach others what I do. I am eager to hear from you. Reach me on LinkedIn, GitHubitHub, or my website.
Posted on December 6, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.