Vertical scroll in JavaScript

Sometimes you need to track how the user scrolls the page.

For example, you can track scrolling down in order to lift the banner to the top of the page and keep it there.

And if the user scrolls the page back to the very top - return the banner to its original position.

If you are reading this article on a wide enough screen, you can see a similar banner on the right.

I first made such a banner for the site HeiHei.ru

You need to use

window.addEventListener('scroll', () => { const scrolled = window.scrollY;

The task is to find the element with the rightBanner class. I know in advance that there will be only one, but in general it does not matter.

'use strict' let rb = document.getElementsByClassName('rightBanner'); /* Find the elements with the rightBanner class */*/ let rightBannerElement = rb[0]; /* We need the first one, and it is the only one anyway */*/ window.addEventListener('scroll', () => { const scrolled = window.scrollY; if (scrolled >= 340) { rightBannerElement.style.position='fixed'; rightBannerElement.style.top='50px'; } /* Fixed the banner after */*/ /* the user scrolled down */*/ else if (scrolled < 340) { rightBannerElement.style.position='absolute'; rightBannerElement.style.top='480px'; /* Put it back, no tricks */*/ /* nothing has to be invented in modern browsers */*/ });

↓ Articles about JavaScript ↓
Development in JavaScript
Sorting an array
Find out the screen width
Find out the type of an element
TicTacToe
Errors

Article author: Andrei Olegovich