Solomon February 2016

Javascript simple add class remove class

<div onclick="myFunction();"> Click Me</div>
<div id="nav" style="" class="hide">
    <ul>
        <li>sample</li>
        <li>sample</li>
        <li>sample</li>
    </ul>
</div>
function myFunction (){
    if ("show"){
        document.getElementById('nav').style.display='none';
            } else if ("hide"){
                document.getElementById('nav').style.display='none';
            }
    }

Onclick the click me btn, i want to show & hide this "nav". using addclass remove class.

Please help me in this pure javascript.

Thanks.

Answers


Albzi February 2016

You can do something like this:

myFunction() {
    document.getElementById("nav").classList.toggle("hide");
}

JSFiddle


Gwendal February 2016

Maybe this will work better ?

<div id="btn"> Click Me</div>
<div id="nav" style="" class="hide">
    <ul>
        <li>sample</li>
        <li>sample</li>
        <li>sample</li>
    </ul>
</div>

<script>
    var menu = document.getElementById('nav');
    document.getElementById('btn').onclick = function() {
        if (menu.className == "hide"){
            menu.className = "show";
        } else {
            menu.className ='hide';
        }
    }
</script>

<style>
    .show {
        display: inherit;
    }
    .hide {
        display: none;
    }
</style>


Jordan Lowe February 2016

Store your element, just for tidier code.

var myElement = document.getElementById('nav');

Using display

myElement.style.display = 'none'; // Hide element
myElement.style.display = 'block'; // Show block elements (div, p)
myElement.style.display = 'inline'; // Show inline elements (span, a)

Using Visibility:

myElement.style.visibility = 'hidden'; // Hide element
myElement.style.visibility = 'visible'; // Show element

Thus using the same code to check for the styles within the if statements.

function myFunction ()
{
    if (myElement.style.display == "none")
        myElement.style.display='block';
    else
         myElement.style.display='none';
 }

Example: http://jsfiddle.net/366aofbo/

Post Status

Asked in February 2016
Viewed 2,825 times
Voted 14
Answered 3 times

Search




Leave an answer