← All Exercises

Compute IntersectionObserver Visibility

intermediatejavascript~15min

Background

Lazy loading and reveal effects use intersection ratios; the ratio is visible area divided by target area, not viewport area.

Problem

Write observeVisibility(state) that computes the visible fraction of a target rectangle and whether it meets a threshold, mirroring an IntersectionObserverEntry.

Input

A JSON string with target and intersection rectangles plus a threshold.

Output

A JSON string with ratio and visible keys.

Sample tests

Sample 1

Input: {"target":{"top":0,"bottom":200,"left":0,"right":200},"intersection":{"top":50,"bottom":150,"left":0,"right":200},"threshold":0.25}
Expected: {"ratio":0.5,"visible":true}

Sample 2

Input: {"target":{"top":0,"bottom":200,"left":0,"right":200},"intersection":{"top":0,"bottom":200,"left":0,"right":200},"threshold":0.25}
Expected: {"ratio":1,"visible":true}

Sample 3

Input: {"target":{"top":0,"bottom":200,"left":0,"right":200},"intersection":{"top":300,"bottom":400,"left":0,"right":200},"threshold":0.25}
Expected: {"ratio":0,"visible":false}

Sample 4

Input: {"target":{"top":0,"bottom":200,"left":0,"right":200},"intersection":{"top":100,"bottom":200,"left":0,"right":200},"threshold":0.5}
Expected: {"ratio":0.5,"visible":true}

Sample 5

Input: {"target":{"top":0,"bottom":200,"left":0,"right":200},"intersection":{"top":0,"bottom":200,"left":0,"right":50},"threshold":0.5}
Expected: {"ratio":0.25,"visible":false}

Your solution

Learning objective

Compute intersection ratios from rectangle geometry and apply threshold semantics like IntersectionObserver.