<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prajwal Shenoy on Medium]]></title>
        <description><![CDATA[Stories by Prajwal Shenoy on Medium]]></description>
        <link>https://medium.com/@prajwal.shenoy?source=rss-5cbe54d182e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5fUdQS1cQarylMaY</url>
            <title>Stories by Prajwal Shenoy on Medium</title>
            <link>https://medium.com/@prajwal.shenoy?source=rss-5cbe54d182e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:30:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prajwal.shenoy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding the Intersection Observer JavaScript API]]></title>
            <link>https://medium.com/whatfix-techblog/understanding-the-intersection-observer-javascript-api-78661000c1f1?source=rss-5cbe54d182e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/78661000c1f1</guid>
            <category><![CDATA[intersection-observer]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <dc:creator><![CDATA[Prajwal Shenoy]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 07:03:45 GMT</pubDate>
            <atom:updated>2021-12-20T07:03:45.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FWpY-CVELNT-h1gTd6-oDw.jpeg" /></figure><p><strong><em>“Sometimes it is the quiet observer who sees the most ” — </em>Kathryn L. Nelson</strong></p><p>In the recent times, JavaScript has introduced quite a number of observers and <strong>Intersection Observer</strong> is one of them.</p><p>Well, what are these <strong>“Observers”</strong>? <br>We know that<strong> Observers </strong>are objects that observe or spot something in real-time. For instance, birdwatchers are those who wait for the birds to come to a specific place and observe them. But not everyone watches crows (or the same bird). i.e. different observers observe different things.</p><p>In the JavaScript world, the very first observer that I came across was the Mutation Observer that looks for changes in the DOM tree. You might have also heard about Resize Observer and Performance Observer. All in all, we can say that <strong>Observer APIs are useful to detect changes in an application</strong>.</p><h3>The Problem</h3><p>In Javascript, performing an action when an element becomes visible to a user has always required the following:</p><ol><li><strong>Identifying the current scroll position</strong>. Adding a scroll event listener to perform this task is easy, but the performance overhead can be costly. You would usually have to write a throttling function to limit the amount of events fired when a user is scrolling.</li><li><strong>Getting the element’s top offset</strong>. Select the element you want to observe in the DOM and get its top offset relative to the element (or viewport) you are detecting. This may seem straightforward until you factor in any lazy loaded or async loaded content that it gets very hard.</li><li><strong>Listener cleanup</strong>. You have to make sure to remove the event listener once you are done performing the action or the logic is run. There might be several such listeners.</li><li><strong>Load on the main thread work</strong>. The function you pass to the event listener will be running on the main thread, and will be running hundreds of times until your condition is met, even with the throttling.</li></ol><h3>The Solution</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API">Intersection Observer API</a> is an excellent solution to this problem. It’s a fairly recent browser API that lets developers hand most of these tasks off to the browser, in a way that is more optimized.</p><blockquote><em>“The Intersection Observer API provides a way to asynchronously observe changes for the intersection of a target element with an ancestor element or with a top-level document’s viewport.” — </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API"><em>MDN Docs</em></a></blockquote><p>This means less code to write, and a lot less overhead to worry about. Intersection Observer allows you to call a function when a target element “intersects” another element. This target element can be anything, but is most commonly (and by default) the viewport.</p><p>The<strong> Intersection Observer API</strong> can be used to observe an element and run a callback function when it <strong>enters or leaves</strong> the viewport (or another element).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_orPu_P3-RH0yDBV6eTQNA.png" /></figure><p>Think of the browser viewport as the blue box and the target element as the pink box in the above image. Initially, the target element is not visible since it is somewhere at the bottom of the page. Now, as the user scrolls down the target element moves up until it eventually overlaps (“intersects”) with the viewport. This is when the target element becomes visible on the page. The amount of this overlap or <strong>intersection</strong> is what the Intersection Observer API observes.</p><h3>Terminologies</h3><p>Before we begin, here are what some terminologies that we are going to use in this article mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*h7Fowhpkgc_hLtlRQAW0rw.png" /></figure><ol><li><strong>Target element</strong> : This is our element of interest whose interaction with the ancestor element (or viewport) that we want to observe.</li><li><strong>Intersection Root</strong> : The ancestor element (or viewport) against which we’ll be observing the intersection of the target element.</li><li><strong>Intersection Ratio</strong> : The measure of how much the target element has intersected with the intersection root. Its value ranges from 0 to 1. An intersection ratio of 0 means that the both don’t intersect at all. Whereas a ratio of 1 indicates that the target element completely intersects with the intersection root.</li></ol><h3><strong>Sample snippet</strong> :</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40d6c18d553ee303d3692c523cc56ecf/href">https://medium.com/media/40d6c18d553ee303d3692c523cc56ecf/href</a></iframe><p>Here’s a sample code of a basic intersection observer. Let us get into the details of each of these parts from the snippet.</p><h4><strong>Creating an Intersection Observer</strong></h4><p>In order to create an Intersection Observer, we use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver">IntersectionObserver</a> constructor. It takes 2 parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ce94e14655d94316a69f8401cb65f7e/href">https://medium.com/media/2ce94e14655d94316a69f8401cb65f7e/href</a></iframe><ul><li>First parameter is the the <strong>callback function</strong> that gets executed asynchronously when the observer notices an intersection. The callback function, when executed, is passed an array of entries, each an instance of <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry">IntersectionObserverEntry</a>. This is an array because the Intersection Observer object can be used to observe multiple target elements, so it just reports intersection changes for these multiple elements together.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f59eb07737182ef26b1443782f90d72/href">https://medium.com/media/6f59eb07737182ef26b1443782f90d72/href</a></iframe><p>The entry object when logged looks something like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*3fRFzDwfKx6H3CahvXz7tQ.png" /></figure><p>For most devs, the two properties that are most likely to be useful are intersectionRatio and isIntersecting. <br>The isIntersecting property is a boolean that is exactly what one might think it is — the target element is intersecting the root element at the time of the intersection change.<br>The intersectionRatio is the percentage of the target element that is currently intersecting the root element. This is represented by a percentage of zero to one, similar to the the threshold provided in the observer’s option object.</p><p>Three properties — boundingClientRect, intersectionRect, and rootBounds — represent specific data about three aspects of the intersection.</p><ul><li>The second is an optional parameter(<strong>options</strong> object) which is used to customise the observer. It’ll define what is the “intersection” that we want to observe. For instance, we may not want to know when an element is about to come into view, but only when it’s fully visible. Something like this is defined through the options parameter.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0513971b4a6a6cf93fa31611254cc76b/href">https://medium.com/media/0513971b4a6a6cf93fa31611254cc76b/href</a></iframe><p>In the options object, the <strong>root</strong> refers to the element that the target element is intersecting against. The root property when set to null, refers to the viewport and is also the default reference when it’s not defined.</p><p>If we want to use any ancestor element as the intersection root instead of the viewport, we can do so by passing an ancestor element reference to the root.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27e1b75fb81d0a4710afc0c7c8ea2a79/href">https://medium.com/media/27e1b75fb81d0a4710afc0c7c8ea2a79/href</a></iframe><p><strong>rootMargin</strong> : A string which specifies a set of offsets to add to the root’s <a href="https://developer.mozilla.org/en-US/docs/Glossary/bounding_box">bounding_box</a> when calculating intersections. The syntax is approximately the same as that for the CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/margin">margin</a> property. The default is “0px 0px 0px 0px”.</p><p><strong>threshold</strong> : A threshold is a value in which the Intersection Observer will execute the callback function <strong>whenever the intersection ratio reaches that value</strong> (either as it increases or decreases)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*fLCluN5TEyZoMDBcVuy3Ag.png" /></figure><h4><strong>Start the Observer</strong></h4><p>We haven’t yet started to observe for intersection until we have called <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/observe">observe()</a> on the observer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b48e1daf6234b07c523f8f689c6bdd03/href">https://medium.com/media/b48e1daf6234b07c523f8f689c6bdd03/href</a></iframe><h4>Stop Observer on a specific element</h4><p>If we have performed something on intersection and we don’t want to further observe the target element, we can call <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/unobserve">unobserve()</a> for that specific target element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f9466c202af5721d6238f65c1f921cf/href">https://medium.com/media/2f9466c202af5721d6238f65c1f921cf/href</a></iframe><h4>Stop Observer entirely (on all its target elements)</h4><p>In case we no longer want to observe the intersection change on any of the target elements for a given observer, we can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/disconnect">disconnect()</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2b1714f12d051ce95d441babbd29817/href">https://medium.com/media/a2b1714f12d051ce95d441babbd29817/href</a></iframe><p>Here’s a <a href="https://intersection-observer-api.arnelle.me/"><strong>little demo</strong></a> by Arnelle Balane where one can see the Intersection Observer in action.</p><h3>Applications</h3><ul><li><strong>Start or stop animation on scroll </strong>: In many situations, we wouldn’t want to perform animations or trigger animations only when element is visible on viewport or intersecting another container element.</li><li><strong>Lazy load images/assets on scroll </strong>: This is the most obvious use case of the Intersection Observer. To load images or resources only when needed or when scrolled and the asset is visible to the user.</li><li><strong>Automatically play or pause videos on scroll </strong>: Another use-case similar to the above one with respect to the media content. No one wants a song/video to be auto-played without having an idea about where it is situated on the page.</li><li><strong>Analyze if an ad is displayed or not and how many times it’s viewed</strong></li></ul><h4>Lazy Loading : An example use-case</h4><p>In order to do this first, we will have a <strong>placeholder image</strong> in all the image elements from the beginning.</p><p>There will be a <strong>data attribute</strong> in all the images which would have the <strong>actual image source(src attribute)</strong>.</p><p>Initially, each image element will have a class saying it isn’t yet loaded, this class will be removed once we load the image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa59b8e8e9a608fc4dcb7be30c5d915c/href">https://medium.com/media/aa59b8e8e9a608fc4dcb7be30c5d915c/href</a></iframe><p>Now we must load images that are getting visible by load and by gradual user interaction ( scroll, click, etc. browser events triggered by user ). To do so we will attach an <strong>intersection observer</strong> to each image elements having a non-loaded class(<strong><em>.</em>lazyLoad </strong>)and whenever the browser intersects the element i.e. the element gets visible it should do the following :</p><ol><li>Replace the placeholder image src with the actual image source</li><li>Load the actual image from <strong>data-src</strong></li><li>Remove the <strong>non-loaded CSS class (.lazyLoad)</strong>, resulting in the element’s exclusion from Observer API.</li><li>Detach or remove the observer attached to that element.</li></ol><p>The above process can be achieved with the below code :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ed49db7dd7e282fa7795b1aa2a769a3/href">https://medium.com/media/1ed49db7dd7e282fa7795b1aa2a769a3/href</a></iframe><p>Here’s the same example I implemented in CodePen for demo purpose.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fprajwal_shenoy%2Fembed%2Fpreview%2FMWEevZx%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DMWEevZx&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fprajwal_shenoy%2Fpen%2FMWEevZx&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/6371ee578410bac330d30f7412a317f1/href">https://medium.com/media/6371ee578410bac330d30f7412a317f1/href</a></iframe><h3>Browser Support</h3><p>The Intersection Observer API is supported on all major browsers except Internet Explorer. Check the browser support <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*QfFmIX83-kqPGBETp4g1uQ.png" /></figure><p>For Internet Explorer, here’s a <a href="https://github.com/w3c/IntersectionObserver/tree/master/polyfill">polyfill</a> available from the W3C that takes care.</p><p>At Whatfix, I have used the Intersection Observer API to get a bunch of cool stuff done and also in troubleshooting element visibility problems.<br>That’s all I have for now. You must have known by now how amazing the the API is in terms of the ease of use, how much more performant, less code and overheads to worry about. Hope you’re all set to leverage its power in your web applications. Happy coding!</p><h3>References</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver">IntersectionObserver - Web APIs | MDN</a></li><li><a href="https://www.section.io/engineering-education/intersection-observer-api/">How to use Intersection Observers in a Website</a></li><li><a href="https://css-tricks.com/an-explanation-of-how-the-intersection-observer-watches/">An Explanation of How the Intersection Observer Watches</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78661000c1f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/whatfix-techblog/understanding-the-intersection-observer-javascript-api-78661000c1f1">Understanding the Intersection Observer JavaScript API</a> was originally published in <a href="https://medium.com/whatfix-techblog">WhatfixEngineeringBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>