• Skip to main content
  • Skip to secondary navigation
  • Skip to footer

recoveryArea

Content Management for Everyone!

  • About me
  • Blog
  • AB Testing
  • WordPress
  • Portfolio

Notify Enter Viewport the proper way: Intersection Observer.

4 February 2020 By iPasqualito

In previous articles I have written about how to track elements when they enter or leave the browsers viewport. The reason why you might want to track this is when you are doing a test on an element that is outside the viewport on page initialisation, you don’t want to count this as a visitor immediately but only when the element is scrolled into view.

If the (changed) element is seen by the visitor, you fire an event, not before. In the past I accomplished this by using something called notify enter viewport. This worked just fine but it came with a lot of caveats.

For instance, notify enter viewport only accepts elements that are already loaded in the DOM. Second, a lot of calculations have to be done inside the function before we know an elements position. It’s complicated.

Modern browsers come with an API that can help us accomplish basically the same in a much simpler way, the Intersection Observer.

Here’s a code example of how I use it in my own AB testing framework.

const observeIntersections = function (config) {
    // loop through all entries in config array
    config.forEach(function (options) {

        document.querySelectorAll(options.element).forEach(function (element) {

            const observer = new IntersectionObserver(function (entries) {
                entries.forEach(function (entry) {

                    if (entry.isIntersecting) {

                        sendDimension({
                            event: 'trackEventNI',
                            eventCategory: abtest.testid + ": " + abtest.testName,
                            eventAction: 'Viewport hit for element [' + element + ']',
                            eventLabel: abtest.variation,
                            eventNonInteraction: true
                        });

                    }
                });
            }, {
                root: null, // use document viewport as container
                rootMargin: "0px",
                threshold: 1 // fire callback as each of these thresholds is reached
            });

            observer.observe(element);

        });

    })
};

observeIntersections([{
        element: 'h4', // the element or elements we want to observe
        tag: 'H4 Element',
        threshold: 1,
        root: null,
        rootMargin: "0px"
    }, {
        element: 'h2#Intersection_observer_concepts_and_usage',
        tag: 'H2 title element',
        threshold: 1,
        root: null,
        rootMargin: "0px"
    }, {
        element: 'iframe.live-sample-frame.sample-code-frame',
        tag: 'IFRAME ELEMENT',
        threshold: [0, 0.5, 1],
        root: null,
        rootMargin: "0px"
    }
]);

Filed Under: AB Testing, JavaScript

Pascal Louwes

Me
Creative, resourceful and innovative Front End Developer / User Experience Optimizer. I love to make stuff work, perform and convert better.

Buzzwords
JavaScript, jQuery, User Experience & Conversion Optimization, Web Strategy, Interaction Design, Accessibility, Wordpress Design, Development & Optimization. check out my full profile

Footer

Office

recoveryArea
Nijverheidstraat 11-1
7511 JM Enschede

KvK: 65594940

Goals

Let's make a more elegant, easy to use internet, accessible for everyone. Let's move forward to an empathic, secular, sustainable future, enabled through science and technology.

Read my full profile

Get in touch

  • GitHub
  • LinkedIn
  • Twitter

Copyright © 2023 · From recoveryArea with

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT