Method 1: Using the sticky value of the position property
The ‘sticky’ value of the position property sets an element to use a ‘relative’ position unless it crosses a specific portion of the page, after which the ‘fixed’ position is used.
The vertical position of the element to be stuck can also be modified with the help of the ‘top’ property. It can be given a value of ‘0px’ to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
- Before scrolling down:
- After scrolling down:
Method 2: Setting the div to be stuck after it had scrolled past
This method attempts to emulate the “position: sticky” method. The element is set to ‘fixed’ or ‘relative’ depending upon whether the user has scrolled past the element.
The element to be stuck is first identified and its current position on the page is calculated. This is done by adding the position of the element relative to the viewport with the current scroll position.
The getBoundingClientRect() method returns a DOMRect object of which the ‘top’ value could be used to get the position relative to the viewport. The current vertical scroll position can be found out by using the window.pageYOffset property. Adding both these values would give us the position of the element on the page regardless of the current scroll position.
The onscroll method is then overridden with a new function to calculate the current scroll position and compare it to the element’s position on the page. If the vertical scroll is more than the element’s position, the position property is set to ‘fixed’ and the ‘top’ property is given a value of ‘0px’. Otherwise, the position is set to ‘relative’ and the ‘top’ property is reset using the ‘initial’ value.
This will compare and make the element stick whenever the user scrolls past the element.
- Before scrolling down:
- After scrolling down
- What is the difference between “screen” and “only screen” in media queries?
- HTML | Screen height Property
- HTML | Screen pixelDepth Property
- HTML | Screen colorDepth Property
- HTML | Screen availHeight Property
- HTML | Screen availWidth Property
- HTML | Screen width Property
- How to center a popup window on screen?
- How to Add App to Home Screen : Progressive Web Apps
- screen command in Linux with Examples
- How to Align modal content box to center of any screen?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.