DEV Community

Cover image for How to know when CSS position sticky get's applied
bhupendra
bhupendra

Posted on • Updated on

How to know when CSS position sticky get's applied

Often we require an element to have a position sticky when we scroll down the page. position: sticky can be thought as a combination of position: relative and position: fixed, an element remains in relative position until a point and then changes to fixed position.



.sticky {
  position: -webkit-sticky;  /* for safari */
  position: sticky;
  top: 0px;
}


Enter fullscreen mode Exit fullscreen mode

above element would be in position relative untill it's 0px from top , after that it changes to position:fixed.

Prior to the sticky position, there was a JS solution to implement above behavior, which would require scroll event listener

Support for position Sticky:

Position-sticky

IE and previous versions of Edge browsers do not support sticky position, it can be resolved using stickyfill polyfill.

Know when an element gets sticky position :

CSS position sticky does not provide an event when the element gets the sticky position, there could be many use cases like changing style when element gets the sticky position, as a user scrolls the page, update a floating TOC widget to the current section, etc..

Intersection Observation API is a Web API which helps to get callbacks fired when certain DOM elements β€œintersect” with one another. Intersection API asynchronously monitors the intersection of a target element with other elements which has a performance advantage over adding callbacks to the scroll events. IE has a polyfill for this API.


Example :

☝ code shows that an element gets a fixed position on scrolling. When fixed, a CSS class is added to the element that changes its background color and updates icon. When sticky position is removed, the class is removed.


Top comments (0)