Help using a button to show and hide an element

I’m working on the Technical Documentation project [code:] but I have a curious problem. When I shrink the browser down, the side-menu enters display: none and #menu-button appears. I’ve tried using some JavaScript to make the button show and hide the #menu-bar, but then when I resize to where the button is gone, the menu is still hidden.

Please help, I’m going insane here! Play with the code and let me know if you’ve figured out how to keep a button that hides / shows the menu while still ensuring the menu is always shown when the viewport width is wide enough.


The problem you are having stems from the fact that you are using the style property to modify styles using JavaScript. As a general rule it’s not a good idea to modify style using that property because what it does is add inline styles to your DOM, thereby rendering your CSS useless. If you want to modify the way something looks from within JavaScript use pre-defined classes and then add and remove them as needed.

The reason why your menu would disappear is your button would set display: none on the menu when hiding it, and even after the window was resized back to desktop size the menu would remain hidden because the inline style would override the CSS.

I simply added a class “displayed” to your CSS file and changed your JS to add and remove that class instead of modifying style.

Here is a link to my fork.


Once you open and close your small screen menu and then enlarge the screen this line never changes back so display is stuck at none. No more button, no way to make the menu items display as inline again.

<div id="menu-bar" style="display: none;">

As @MadOgre states using inline style is probably not the best way to do this anyways. Toggling a class styled with css to hide / unhide your menu is the way to go.

You’re a life saver. That explanation was great. Works perfect, thanks!

1 Like