2
<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.

3 Answers 3

2

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>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this, This is working fine. How do i do instant of display - block & inline. I want to do this by ADD class & remove class..
Not sure to understand what you want, you need to have too classes like hide and display ? Don't forget to upvote if I helped you :) @user3852173
I am having 2class for the id=nav onclick btn i want to add & remove class in nav = hide & show.
2

You can do something like this:

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

JSFiddle

1 Comment

How do i implement this? Unexpected token - error message its showing
0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.