JavaScript scroll

The onscroll event in JavaScript occurs when a scrollbar is used for an element. The event is fired when the user moves the scrollbar up or down. We can use the CSS overflow property for creating a scrollbar.

In HTML, we can use the onscroll attribute and assign a JavaScript function to it. We can also use the JavaScript's addEventListener() method and pass a scroll event to it for greater flexibility.

Syntax

Now, we see the syntax of using the onscroll event in HTML and in JavaScript (without addEventListener() method or by using the addEventListener() method).

In HTML

In JavaScript

In JavaScript by using the addEventListener() method

Let's see some of the illustrations to understand the scroll event.

Example - Using onscroll attribute in HTML

In this example, we are using the HTML onscroll attribute. There is a paragraph element with id = "para" on which we are applying the onscroll attribute. When the user scrolls the paragraph, the color and the background color of the paragraph will change.

Test it Now

Output

JavaScript scroll

After scrolling the bordered text on the screen, we will get the following output -

JavaScript scroll

Now, we will see how to use onscroll event using JavaScript.

Example - Using JavaScript

Test it Now

Output

JavaScript scroll

After scrolling the bordered text on the screen, we will get the following output -

JavaScript scroll

Example - Using addEventListener()

Test it Now

Output

JavaScript scroll

After scrolling the bordered text on the screen, we will get the following output -

JavaScript scroll




Contact US

Email:[email protected]

JavaScript scroll
10/30