简体   繁体   中英

Jquery if visible show another div, else hide

I am trying to have an whole page overlay, when mega menu is active. I am trying something like this:

function overlay_toggle() {

        if ($('.mega-sub-menu').css("visibility") == "hidden") {

            $('#twc-page-overlay').css({ "visibility": "hidden" });
        }

        else {
            $('#twc-page-overlay').css({ "visibility": "visible" });
        }

    }

Currently its doing doing the job. Any ideas what I am missing here?

Thank you!

HTML something like this:

<header>
   <nav>
      <ul>
         <li>
            <ul class="mega-sub-menu"></ul>
         </li>
      </ul>
   </nav>
</header>

<div id="twc-page-overlay"></div>

That won't work, just use .is(":visible") to check visibility, and .show() to make it visible and .hide() to hide it

 if ($('.mega-sub-menu').is(":visible") === false) { $('#twc-page-overlay').hide(); } else { $('#twc-page-overlay').show(); }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header> <nav> <ul> <li> <ul class="mega-sub-menu"> <li>Heheh</li> </ul> </li> </ul> </nav> </header> <div id="twc-page-overlay">Hello</div>

You can write this in one line:

$('#twc-page-overlay').toggle($('.mega-sub-menu').is(':visible'));

If you want to use visibility rather than display , you can do the same thing with toggleClass:

.hidden { visibility: hidden; }

$('#twc-page-overlay').toggleClass('hidden', $('.mega-sub-menu').is(':hidden'));

Both .toggleClass() and .toggle() accept a boolean value to apply/remove or show/hide respectively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM