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
, oropacity: 0
element. - Detect if an anchor element becomes untabbable.
2
Answers
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:
Element.closest()
method to query whether an element (or an ancestor) has theinert
orhidden
attribute.Element.getAttribute()
method to check if an element is untabbable (i.e. has itstabindex
attribute with a negative value).Element.getBoundingClientRect()
orElement.getClientRects()
method to find out whether an element is visually hidden.getComputedStyle(element)
function to find out whether an element is declared to be hidden.MutationObserver
to detect attribute and DOM-tree changes.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).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. :
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’);