Reputation: 227
I have a single page site made with <div>
tags moving, hiding, ect.. I need to be able to have the back button control the functions running my divs.
I have been doing my research no how to do this and came across this article.
I have included this code in my site and it works great for updating the URL with incrementing hashtag numbers every time the user clicks a button with the doclick() function attached.
var times = 0;
function doclick() {
times++;
location.hash = times;
}
window.onhashchange = function() {
if (location.hash.length > 0) {
times = parseInt(location.hash.replace('#',''),10);
} else {
times = 0;
}
document.getElementById('message').innerHTML =
'Recorded <b>' + times + '</b> clicks';
}
I have 4 buttons on my site calling doclick()
<div onClick="edit(); doclick()">Editorial</div>
<div onClick="vfx(); doclick()">VFX</div>
<div onClick="audio(); doclick()">Audio</div>
<div onClick="color(); doclick()">Color</div>
I am not experienced enough to see how to do what I need though.
Now that I am storing every click in a new hash, how can I use that data to call specific functions I already have setup? Or maybe there is a better way to tweak so that instead of just adding #1, #2 etc.. URL will reflect page name. Like www.site.com/vfx - And I could use that information to call a function.
Example Usage:
Upvotes: 0
Views: 2650
Reputation: 2202
Along with HTML5, there is a History API, which allows you change the state of the browser, and change the URL path-name, but do not reload the page, when the buttons forward
or backward
is clicked, the page will be act just like you page has been reloaded, but it's not.
Please check this example:
var target = document.querySelector(".content");
//Initiate the state.
history.replaceState({
title: document.title,
content: target.innerHTML,
}, document.title);
//When the buttons forward or backward is clicked, change the state of
//browser, and replace the target's content.
window.onpopstate = function(e) {
if (e.state) {
document.title = e.state.title;
target.innerHTML = e.state.content;
}
};
//Assuming you're using Ajax to load remote data.
$.get("/something", function(data){
history.pushState({
title: data.title,
content: data.content,
}, data.title, data.url);
document.title = data.title;
target.innerHTML = data.content;
});
If you are still not understand what I'm saying, please check my recent project's website, though it uses WebSocket to load remote data, you can see when you click the items of documentations, the page won't be reload, but the content and URL will be modified.
http://cool-node.hyurl.com:3000/Docs
And for convenience, I have wrapped this API to a single plugin, you can check it out at
https://github.com/Hyurl/soft-loader
Or, by the way, you don't actually need to reload remote data, this is just an example, you can store you content anywhere you want, remote or local in the <body>
, etc.
Upvotes: 2