简体   繁体   中英

Toggle (show/hide) element with javascript

By using this method I can show/hide an element by using 2 buttons:

<script type="text/javascript">
function showStuff(id) {
        document.getElementById(id).style.display = 'block';
}
function hideStuff(id) {
    document.getElementById(id).style.display = 'none';
}
</script>

<input type="button" onClick="hideStuff('themes')" value="Hide">
<input type="button" onClick="showStuff('themes')" value="Show">
<div id="themes" style="display:block">
    <h3>Stuff</h3>
</div>

Is there a method to use a single button?? Maybe if & else?

You've already answered your question...the use of if / else :

function toggle(id) {
    var element = document.getElementById(id);

    if (element) {
        var display = element.style.display;

        if (display == "none") {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
    }
}

This won't be completely foolproof, in case you are hiding/showing inline or inline-block elements, or if you are using non-default values for display on elements...such as setting a div's display to "inline" (for whatever reason) and then trying to use this function

Yes if/else will work

function toggle(id){
    var elem = document.getElementById(id);
    if(elem.style.display == 'block'){
        elem.style.display == 'none'
    } else if(elem.style.display == 'none'){
        elem.style.display == 'block'
    }
}

I think you mean something like this:

 function toggle(id){
var elem = document.getElementById(id);
if(elem.style.display == "block"){
    elem.style.display="none";
} else {
    elem.style.display="block";
}

}

Here is an alternate solution. Instead of using document.getElementById , you can also use document.querySelector which returns the first Element within the document that matches the specified selector, or group of selectors.

Solution Code:

function toggleShow() {
    var elem = document.querySelector(id);
    if(elem.style.display == 'inline-block'){
      elem.style.display="none";
    }
    else {
      elem.style.display = "inline-block";
    }
  }

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