Objective: Change the properties of CSS Stylesheet instead of HTML CSS using Javascript.
Current Issue: using document.getElementById("foo").style.display = "none" causes changes in HTML document that removes Media Query functionality
My website has a button that changes the display of a sidenav bar on smaller screens. This button is not available on screen sizes greater than 768px. The website is dynamic, so the button shows up when the screen is small enough. When the button is clicked, the sidenav (initially set to display:none), is set to display:block, which can then be closed again.
Once the sidenav is closed in a screensize < 768px, and the screen is increased to a size > 768px, the media query no longer changes the display to block because the Javascript changes the HTML, which overwrites the CSS media query.
Below is the code and changes the Javascript does to the HTML.
HTML Before:
<div id="sidenav">foo</div>
<!-- button to change sidenav -->
<div id="menu-button" onclick="openCloseNav(this)"></div>
Javascript
function openCloseNav(x){
if(x.classList != "change"){
document.getElementById("sidenav").style.display = "none";
}
else{
document.getElementById("sidenav").style.display = "block";
}
}
CSS
#sidenav{
display:none;
}
@media only screen and (min-width: 768px){
#sidenav{
display:block
}
}
HTML After div id="menu-button" is clicked twice
<div id="sidenav" style="display:none">foo</div>
<!-- button to change sidenav -->
<div id="menu-button" onclick="openCloseNav(this)"></div>
I have tried a few different things such as attempting to detect screenwidth in Javascript like this:
var currentWidth = window.screen.availWidth;
function showSideNav(){
if (currentWidth >= "768"){
document.getElementById("sidenav").style.display = "block";
}
}
to no avail. If the snippet above does work, I don't know where to place it in my HTML.
Question:
What can I do to make it so that the sidenav will show even after the menu-button div is clicked on screen sizes > 768px?
display = none, have JS add a class to your elementdocument.getElementById('foo').classList.add('hide')(or whatever you choose to name it), which then answers to the CSS. Allowing you to set media query parameters on that class in accordance to what you want to accomplish.body.sidenavShown foo { ... }display:nonefrom the main#sidenavin my CSS stylesheet and made a.hide-navclass. I suppose I could change this to just.hideif I need to hide other things, as well, and just apply for reduced bloat @Scott Marcus suggested.