Updated JS only version: http://jsfiddle.net/0uk0g0qq/4/ (works everywhere)
:target
implementation is buggy in ie. so previous one wasn't working. hash changes only affects css when user directly does something on page, click button that changes hash and unfortunately back button is not considered part of the page
The all the javascript you need is this:
var menu = document.getElementById('menu');
window.addEventListener('hashchange', function(e) {
if (location.hash != "#menu") {
menu.style.display = "none";
} else if (location.hash == "#menu") {
menu.style.display = "block";
}
});
Css Only Version:::
You can do it using just css only. It's time you learned about :target
selector.
It lets you apply style to whatever is url hash fragment and is the id of element on page.
Demo: http://jsfiddle.net/0uk0g0qq/1
So i hide menu by default, but if it matches i show the menu. Since hastags in url affect browser history it accomplishes what you asked for.
It was pretty awesome first time i learned it.
#menu:target {
display: block;
}
the whole code:
body {
background-color: cornsilk;
}
.cont {
width: 500px;
margin: auto;
}
#menu {
display: none;
position: absolute;
top: 0; bottom: 0; left: 0; right: 0;
height: 100%;
background-color: rgba(0,0,0,.3);
margin: auto;
}
#menu > ul {
width: 200px;
list-style-type: none;
background-color: #fff;
margin: auto;
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
}
#menu > ul li {
padding: 20px 10px;
}
#menu:target {
display: block;
}