1

I have an interactive element displayed only within the CSS media query which toggles the display of another element (the nav element) from none to block. Outside the media query (any display width greater than 580px) the nav element display is set as block. When I toggle the display within the media query and set the nav to display none, then re-size the browser to a width greater than 580px the nav element is still set to display none. How can I make so that toggling the display of nav within the media query will have no impact on its display outside of the media query?

<!-- Toggle Display
	// click on the element
	function toggle(e, id) {
		var el = document.getElementById(id);
		
		el.style.display = (el.style.display == 'none' || el.style.display == '') ? 'block' : 'none';

		// save it for hiding
		toggle.el = el;
		

		// stop the event here
		if (e.stopPropagation) e.stopPropagation();
		e.cancelBubble = true;
		return false;
	}

	// click outside the element
	document.onclick = function() {
		if (toggle.el) {
			toggle.el.style.display = 'none';
		}
	}
//-->
nav {
  color: white ;
  float: right ;
  margin: 0 10px 0 0 ;
  display: block ;

}


nav a {
  margin-right: 25px ;
  padding: 5px 4px 2px 4px ;
  display: inline-block ;
}

.nav-text { 
  display: none ; /* replaced by icons */
  font-size: 18px ;
}

@media all and (max-width: 580px) {
   
   nav {
     display: none ;
     float: left ;
     width: 100% ;
     margin: 3px 0 0 0 ;
     clear: both ;
   }
   
   .menu {
     display: block ;
  }
  
    nav a {
     display: block ;
     background: gray ;
     color: white ;
     padding: 10px 20px ;
     width: 100% ;
     border-bottom: 1px solid #ccc ;
  }
  
}
<header>

  <div onclick="toggle(event, 'nav')" class="menu" tabindex=0> 

    <!-- Menu icon -->
 
  </div>

  <nav id="nav">
    <a href="/"><span class="nav-text">Home</span></a>
    <a href="#"><span class="nav-text">About</span></a>
  </nav>

</header>

1 Answer 1

2

When you set display:none with your Javascript code, that gets set as an inline style, which overrides anything within your CSS files, media queries or otherwise.

The easiest way out of this would be to add !important to display:block inside your media query, but that's a bit sloppy.

Alternatively, if you really want to use this toggle functionality with Javascript, you can add a listener to the window to detect screen width changes. So, if the window is sized above 580px (or whatever size you desire), it can check and make sure that any inline css is cleared out.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.