lxg95
lxg95

Reputation: 573

How to check if an Element with a certain Classname is visible?

I'd like to check if there is any Element with the Classname settingsBox is visible. I created this function, but it doesn't work:

function noOptionsOpen(){
    $(".settingsBox").each(function (){
        if ($(this).is(":visible")) return false;
    })
    return true;
}

I guess, the inner Function returns fals if ther is anything visible with that classname, but after jumping out of it, it still always return true, right? I just don't know how i can fix that?

Upvotes: 2

Views: 1465

Answers (2)

Mister Jojo
Mister Jojo

Reputation: 22265

that ?

const
  isHidden = el => (window.getComputedStyle(el).getPropertyValue('visibility')==='hidden')
, noOptionsOpen = classN => [...document.querySelectorAll(`.${classN}`)].some(isHidden)
;

console.log( 'some elements are not visible ? -> ', noOptionsOpen('settingsBox') )
#parent >div:nth-of-type(3) {
  visibility: hidden;
}
<div id="parent">
  <div class="settingsBox">aa</div>
  <div class="settingsBox">bb</div>
  <div class="settingsBox">cc</div>
  <div class="settingsBox">dd</div>
  <div class="settingsBox">ee</div>
</div>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because you cannot return from the noOptionsOpen() function within the anonymous handler function in each(). One way around this would be to define a variable and update it within the loop, before returning it:

function noOptionsOpen() {
  let optionsOpen = true;
  $(".settingsBox").each(function() {
    if ($(this).is(":visible")) 
      optionsOpen = false;
  })
  return optionsOpen;
}

A much better was would be to use :visible in a single selector and checking the length property. This almost makes the function redundant, but depends on your use case:

function noOptionsOpen() {
  return $(".settingsBox:visible").length === 0;
}

// As above in ES6:
let noOptionsOpen = () => $(".settingsBox:visible").length === 0;

Upvotes: 2

Related Questions