Bouhraoua Bouhraoua - 1 month ago 7
CSS Question

Hiding and showing element based on screen size

I'm trying to make button that will hide and show menu when web page is being displayed on smaller screens. I want to keep the whole menu when the display is wider than 640px. I'm only allowed to use CSS and JavaScript.

Here is the JS function I wrote:

var b = document.getElementById ("menu-button");
b.addEventListener("click", showMenu, false);
var i = 0;
function showMenu () {
i++;
if(i % 2 == 1)
document.getElementById("menu").style.display = "block";
else
document.getElementById("menu").style.display = "none";
}


It is working when displaying the page on smaller screen.

When I click the button to hide the menu (that changes "menu" display to
none
) and then increase the size of the page, my menu does not appear when the screen becomes larger than 640px.

This media media query does not do the job:

@media screen and (min-width:640px) {
#menu {
display: block;
}
}

Answer

You need to add !important to the CSS property, like:

 #menu { display:block!important; } 

Your Javascript adds style attribute to the element, which has higher priority than any internal or external CSS styles, unless they "are" !important.

What you can also consider doing to avoid that is to toggle some CSS class in your Javascript instead of setting style attribute. This way you avoid using !important.

Comments