简体   繁体   中英

Toggle (show/hide) a sub menu with JavaScript

I am developing a site where I can NOT use jQuery (please, no comments on how good is it, it's prohibited) and I need to reproduce something like .toggle() just for show/hide a div with a class.

I've a group of boxes with a arrow, this arrow can expand a submenu. Let's see an example:

<div class="box">
    <div class="box-utils">
        <a href="#" class="up">&nbsp;</a>
    </div>

    <h2>Example case</h2>

    <div class="box-submenu hidden">
        <ul />
    </div>
</div>

I need that click on the <a /> inside the <div class="box-utils" /> shows/hide the box-submenu class. When it's hidden, the <a /> needs to have class="down", when it's not hidden it needs to be class="up". This also needs to work with more than one case in the same page.

Can someone help me?

Thank you in advance!

Create a toggle function like the one below, provide an id attribute on your DIV (call it box-submenu or something) and call the function from your anchor, and use the ID to lookup whatever you want to hide/show.

<script language="javascript"> 
function toggle() {
    var ele = document.getElementById("box-submenu");
    var link = document.getElementById("linkId");
    if(ele.style.display == "block") {
        ele.style.display = "none";
        link.className = "down";
    }
    else {
        ele.style.display = "block";
        link.className = "up";
    }
} 
</script>

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