2

I am writing a simple function to toggle a menu for a mobile site but cannot get my code to work. I have looked at examples online and have followed them but I can't achieve to toggle the menu off.

<script type="text/javascript">
function toggleMen(id) {    
     var a = document.getElementById(id);
    if(a.style.display='none'){
        a.style.display='block';
    }
    else if (a.style.display='block'){      
        a.style.display="none";
    }
}
</script>

As you can see I am trying to simply check what value display is at and set it accordingly. I know there may be more efficient ways but for now this is all I need.

Method Call:

toggleMen('menu');

3 Answers 3

1

The = operator is for assigning values.

The === (or == if you're feeling lucky) operator is for comparing values.

if (a.style.display === 'none') {
    a.style.display = 'block';
} else { 
    a.style.display = 'none';
}

See here for more information on the difference between === and ==.

BTW Here's a working fiddle. After tinkering a bit, I realized your problem may have been that the original display wasn't set to anything (a.display.style was equal to ''), so your conditional was never firing on either condition. If that is the case, with the above changes, it will now fire the else on the first pass, and then alternate every pass after that. (And if that isn't the case, the above changes should still do the trick)

Sign up to request clarification or add additional context in comments.

Comments

0

try a.style.display == 'none' instead of a.style.display = 'none'

1 Comment

I have tried before but I just tried again to no avail.
0

Try this HTML:

<button onclick="toggleMen('menu');">Button</button>

<div id="menu">
    <div id="gripMenu">
    <div class="menuItem">Home</div>
    <div class="menuItem">Cake Builder</div>
    <div class="menuItem">Order</div>
    <div class="menuItem">Cakes</div>
    <div class="menuItem">Info</div>
    <div class="menuItem">About</div>
</div>

... And this JS:

function toggleMen(id){
    var a = document.getElementById(id);

    if(a.style.display === 'none'){
        a.style.display = 'block';
    } else {
        a.style.display = 'none';
    }
}

3 Comments

Not working, although looks correct. This is a real head scratcher
Its not a wrong ID. It does change to block. I just cant change back to "none"
Remove ALL your css ... and test ... it works without your CSS!

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.