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');

Shehary
  • 9,926
  • 10
  • 42
  • 71
Anon Omus
  • 383
  • 4
  • 12
  • 25

3 Answers3

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)

Community
  • 1
  • 1
sfletche
  • 47,248
  • 30
  • 103
  • 119
0

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

Thi Tran
  • 681
  • 5
  • 11
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';
    }
}
Ole Sauffaus
  • 534
  • 3
  • 13