-1
echo "<div id=\"userinfo\"><p><strong>$username</strong></p><p>Bids: <strong>$bids</strong></div>
            <script>

                var usn = document.getElementById('userstuff');
                menu = document.getElementById('userinfo');
                if (usn) 
                {
                    usn.addEventListener('click',toggle_menu);
                }


                function toggle_menu()
                {
                    alert('clicked');
                    if (menu.style.display == '')
                    {
                        menu.style.display='block';
                    }
                    else if (menu.style.display == 'block')
                    {
                        menu.style.display='';
                    }
                }

            </script>";

This code works on the first click. By default, the display value in menu is set to 'none'. The first click, the user is alerted 'clicked' and the menu becomes visible. However, on more clicks, the user is alerted 'clicked' but the menu does not become invisible and the 'hidden' alert does not show.

CLASSIFIED
  • 13
  • 5

1 Answers1

3

Remember that = is for assignment, use == for comparison. Another problem is that checking menu.style.display only checks inline styles of the node, such as:

<div style="display: none"></div>

Thus if the style is not set comparison will fail. '' comparison instead of 'none' works because by default the properties are empty strings if not set, seen here.

A few other recommendations: always declare your variables with var to prevent global scope pollution with many global variables. Here's the final JavaScript:

var usn = document.getElementById('userstuff'),
    menu = document.getElementById('userinfo');

if (usn) {
    usn.addEventListener('click', toggle_menu);
}

function toggle_menu() {
    alert('clicked');

    if(menu.style.display == '' || menu.style.display == 'none') {
        menu.style.display = 'block';
        return;
    } else if (menu.style.display == 'block') {
        menu.style.display = 'none';
        return;
    }
}
Andrew Li
  • 55,805
  • 14
  • 125
  • 143