Search code examples
javascriptazureobservers

How to use the observer to check if a div is visible or not? (maybe Azure server problem?)


I need to check without further action if an element on my page is currently visible (this is being set either by button click or function call).

The observer seems to be the right tool from what I have read so far. On my local machine everything works fine. But on my Azure test server I am getting the following error:

Uncaught TypeError: Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element'

Here is the code I am using:

function setStatus() {
    var target = $('#sidebar_container');

    var ro = new ResizeObserver(() => {
        if (target.is(':visible')) {
            $("i.fa-user").addClass("active");
        } else {
            $("i.fa-user").removeClass("active");
        }        
    });

    // Observe element
    ro.observe(target);
}

Is there something wrong with the code (although it's working on localhost) or is there a setting on the Azure server I would have to check?


Solution

  • From the code you posted, it looks like you are testing this functionality on localhost by resizing your window.

    I'm saying this because, to check if an element has come into the viewport, you should use the Intersection Observer, not the Resize Observer.

    You'll find a deep dive into how this observer works in the MDN link above.

    To simply check if an element is inside the viewport (so it should be "visible") this is a possible solution:

    // Get a reference for the target element
    let element = document.querySelector('#sidebar_container');
    
    // Create a function that will handle any intersection between some elements and the viewport.
    let handleIntersection = function (entries) {
    
        // Loop through all the observed elements
        for (let entry of entries) {
    
            // Check if the element is intersecting the viewport
            if (entry.isIntersecting) {
                console.log("The following element is visible in the viewport: ", entry.target);
                // ...
            }
        }
    }
    
    const observer = new IntersectionObserver(handleIntersection);
    
    observer.observe(element);
    

    Also, you should pass to the observer an actual DOM element, not the jQuery wrapper. For this, it would be probably better to just use document.querySelector to select the element rather then jQuery. In the devtools the $ sign is a shortcut to the querySelector, so if you were trying this code directly through the devtools, this might have triggered some confusion.