Alex_Flowers
Alex_Flowers

Reputation: 53

JavaScript event that fires when all of the certain elements get display: none

So, say, I have 5 html elements that are hidden via class that has a display:none property. Then there's a button which removes that class on one of these elements with every click (5 clicks results into all 5 elements being visible). And then all of these 5 elements have "their own button" that adds back this class with display:none when clicked.

Now, I want some other element to get invisible when all of these elements are invisible as well. And then, when at least one of them is visible (doesn't have display:none), I want this other element to be visible as well.

To complete the task, I was trying to use the MutationObserver.

let my_observer = new MutationObserver(function(mutations) {...}

elements_nodelist.forEach((my_element) => {
    observer.observe(my_element, {attributes: true, attributeFilter: ["class"]});
  })

But unfortunatelly, it reacts to just any class changes, it doesn't only watch the visibility state, or only this particular class changes. yes, I can get a mutation.oldValue information and get to the element.classList, but I can't figure out the way to use it to solve all this.

Upvotes: 1

Views: 136

Answers (1)

Chema
Chema

Reputation: 365

You can check if all your hidden elements have the hidden class:

const myHiddenElements = [...document.querySelectorAll('.my-hidden-element')];

const isAnyVisible     = myHiddenElements.filter( elm => elm.classList.contains('hidden-class') ).length < myHiddenElements.length;

if( isAnyVisible ) {
    // Do what you want
}

Upvotes: 1

Related Questions