What is the main difference between rootMargin & threshold in Intersection Observer API?
Asked Answered
M

1

6

As I learned that once you have set rootMargin:"0px", it means that the effect will be produced when the element you have selected has been completed visible on screen and have 0px of margin with respect to the viewport or any relative.

In threshold property, it has values from 0% to 100% also denoted as 0 to 1. It means that if the value is 1, the callback will run once the element is 100% visible on the viewport.

Please highlight the differences between them.

Miter answered 27/9, 2020 at 12:30 Comment(0)
P
9

rootMargin is the rectangular bounding box around your root that you can adjust to trigger intersections. By default, this is your viewport. Use this to trigger an intersection when an element is within a certain area of the root i.e. trigger when my observed element reaches 25% of the viewport or 50px of the viewport. Values can be % or px. i.e. rootMargin: '0px 0px -50px' or rootMargin: '0px 0px -25%'.

threshold is the percentage of the observed element within the root. Use this to trigger an intersection when a percentage of the observed element is within the root i.e. trigger when 65% of my element is within the viewport (root). Values are % based between 0 and 1. i.e. threshold: .65

JSFiddle Demo

Pickar answered 16/3, 2021 at 19:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.