Reputation: 173
Okay, I'm trying to design a mobile version of my site and am stuck on my menu.
Basically at the moment I've got a simple onClick running on the page so if the user decides they don't want to view click whats on the menu then they can click the page and the menu disappears.
But what I really want is a way of using the back button on the browser to return from the menu. I'm guessing it takes some kind of event or setting something, but am at a loss.
I'm a newbie, so be gentle, I'm hoping the community can help me a little as to where to start.
My main question is how to use the back button on a browser within my HTML or JavaScript, any ideas as to how to proceed would be greatly appreciated.
Upvotes: 4
Views: 2822
Reputation: 18097
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;
}
Upvotes: 5