skip to Main Content

Is it possible to detect when elements are hidden such as from inert or hidden?

I have a sitemap page and my links use an IntersectionObserver and the mouseover event to detect when links are very visible to preload data. Especially on a page with a lot of links like a sitemap page this can get quite expensive or at least a little annoying and noisy on the profiler.

One of the ideas I would like to try would be to disable the observer and prefetching logic when links are hidden inside a disclosure widget a little like the details element or in my case an accordion.

I can explicitly feed the data in (in my case probably with a React provider) or just not use that functionality on this pages links. But I thought it might be elegant to detect if there was a way to detect if the element is hidden or made inert inside a the disclosure widget.

So basically one option I want to explore would be:

  • Detect if an anchor element is underneath an inert, hidden, or opacity: 0 element.
  • Detect if an anchor element becomes untabbable.

2

Answers


  1. I don’t know of any native way to detect what you’re looking for, but you should be able to build it yourself. Here are some pointers:


    Personally, I recommend to instead use an explicit way of stating whether a link should preload, e.g. the presence/absence of a certain attribute.

    Such an attribute would allow for more flexibility: The IntersectionObserver would not have to itself compute whether a link should preload (repeatedly), and the attribute may be set initially (e.g. in the HTML source) or deferred (e.g. when entering the viewport before preloading).

    Login or Signup to reply.
  2. You can use somthing like this to get all the elements which are hidded. I have used getComputedStyle function to get the final CSS applied to the elements. :

    const anchorElement = document.querySelector('a');
    const computedStyle = window.getComputedStyle(anchorElement);
    
    // Check if hidden
    if (computedStyle.display === 'none' || computedStyle.visibility === 'hidden' || computedStyle.opacity === '0') {
      
    }
    

    If you want to check if the anchor element is keyboard-focusable or not, you can use something like this :
    const anchorElement = document.querySelector(‘a’);

    // Check if untabbable
    if (anchorElement.tabIndex === -1) {
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search