I have a mobile menu button (only viewable with display:block by using media queries). When the button is clicked, my main "mobile" menu appears - I do this using simple javascript code (see below).
The problem ... if I click the button to expand the menu (changing the inline style from display:none to display:block), and then increase the browser size ... my menu doesn't disappear anymore. So, the inline style doesn't recognize the media query...
Below is the script that expands my menu...
<!-- Menu Expander / Toggle Visibility -->
<script type="text/javascript">
function toggle_menu(id) {
var e = document.getElementById(id);
if (e.style.display == 'block') e.style.display = 'none';
else e.style.display = 'block';
}
</script>
Here are some of the styles.... you'll see the menu-mobile (which is the actual menu) and the mobile-menu-but (which is the button) is hidden (with display:none). When the browser window is reduce, the button appears (with display:block in the media query), but the menu is still hidden. Then when you click the javascript button, the inline style display:block is added to set for the mobile-menu.
#mobile-menu-but, #menu-mobile { display:none; }
#menu a, #menu a:link { padding: 15px 16px 12px 16px; }
@media (max-width: 790px) {
/* Switch to Mobile Menu when too long */
#menu { display:none; } /* Hide Main Menu */
#mobile-menu-but { display:block; float:right; margin:0 20px 0 0; height:50px; padding:5px 0; }
#mobile-menu-but a { float:right; }
.menu-txt { margin:10px 10px 0 0; float:right; }
#menu-mobile { width:100%; background-color:#000; text-transform:uppercase;
font-size:16px; font-family:"AvantGarde", "Helvetica Neue", Arial, Helvetica, sans-serif; } }
Instead of directly manipulating element styles, you can add and remove class values in order to change element appearance. The rules for the class(es) can be affected by media queries because they'll go right into the stylesheet.
Modern browsers provide the .classList
API:
function toggle_menu(id) {
var e = document.getElementById(id);
if (e.classList.contains("showing"))
e.classList.remove("showing");
else
e.classList.add("showing");
}
Now, in your CSS, you can have:
#menu { display: none; }
#menu.showing { display: block; }
If you only want to show the menu when the screen is big, add this after those lines above:
@media screen and (max-width: 700px) { /* or whatever size you want */
#menu.showing { display: none; }
}
(There are other strategies for arranging rules in media queries, depending on what you're trying to do.