For a sidemenu i've created a toggle with a simple javascript:
function myFunction() {
var x = document.getElementById("left");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
This works fine on large screens, but on a mobile/smaller device i'd like to start with the sidemenu closed. I've added css to change the display from 'block' to 'none':
@media only screen and (max-width: 600px) {
#left {
z-index:10;
position: absolute;
background-color: #ffffff;
display:none;
}
}
When you initially open the page on a small device you have to click the menubutton twice to activate the script. How could i add a 2nd check to the script to include width? I thought something with adding 'matchmedia' but can't get it to work.
I've created a basic fiddle @ https://jsfiddle.net/zouLf8ey/1/
function myFunction() {
var x = document.getElementById("left");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#left {
height: calc(100% - 40px);
width: 250px;
float: left;
overflow-y: auto;
overflow-x: hidden;
display: block;
padding: 12px;
border-bottom: 1px solid #ededed;
border-right: 1px solid #ededed;
}
@media only screen and (max-width: 600px) {
#left {
z-index: 10;
position: absolute;
background-color: #ffffff;
display: none;
}
}
#right {
width: auto;
height: calc(100% - 40px);
overflow-y: auto;
overflow-x: hidden;
display: block;
padding: 12px;
border-bottom: 1px solid #ededed;
}
<div class="scherm">
<div class="schermtekst">
<button id="menu-toggle" title="show/hide index" onclick="myFunction()">Menu</button>
<div id="left">
<ul id="nav">
<li><a href="#">link 1</a> </li>
<li><a href="#">link 2</a> </li>
<li><a href="#">link 3</a> </li>
<li><a href="#">link 4</a> </li>
</ul>
</div>
<div id="right">
<h1>
<a name=""></a>Title
</h1>
<p>
Good: When the screen is smaller than 600px the menu is hidden. With one click on 'menu' the toggle opens the menu. <br/> Bad: When the screen is larger than 600px you have to click the 'menu' button twice. After that all works fine. This is due
to the difference between display 'none' and 'block'. (on a smaller screen i don't want to clutter the layout with the menu in sight. <br/>
<em>How can i properly change the script below in the html? I tried with setting an if for width && display: block</em></p>
</div>
</div>
</div>
Any help would be appreciated! Cheers, Ed'