so say I set a hash when i do an ajax call:
example: http://example.com/#hash.html
if I load another page and click on the backbutton, how would i detect the hash and extract the url on load?
The rest I got already covered :).
If you need more code, please tell me. btw, i'm using jquery.
There is an event, hashchange
, but it's only supported in Firefox 3.6, IE8 and I assume the latest Chromes and Safaris.
For best support, detect the hashchange
event, and if not present, use a polling function with setInterval()
.
So you would do something like...
(function() {
var hash = window.location.hash;
if ('onhashchange' in window) {
window.onhashchange = hashChanged;
} else {
setInterval(function() {
if (window.location.hash != hash) {
hash = window.location.hash;
hashChanged();
}
}, 500);
}
var hashChanged = function() {
alert('Hash has changed!');
};
})();
You have a couple of options.
The most obvious one is
window.location.hash;
...which has been part of actual JavaScript for some years (more information here or by googling "javascript location hash").
There is also a jQuery plugin called jQuery.Url which has a lot of nice features for working with URLs.
$(function() {
var page = window.location.hash;
if (page == "") page = "somedefaultpage.html";
$("#content").load(page);
});
If you've wired up your navigation properly the page loaded into your content element should already be there since the browser had to navigate to that #hash
Simple example using window.location.hash to load appropriate hash content set in url while navigating back and forth.
Hope this helps someone...cheers!!
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
a{
text-decoration: none;
color:#999;
font: arial;
}
.content{
width: 50%;
height: 30px;
border:1px solid darkorange;
padding: 3%;color:#999;
}
</style>
<body>
<div class="box">
<a id="hash1" href="">Add Hash1</a>
<a id="hash2" href="">Add Hash2</a>
</div>
<div class="content"></div>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$(".box a").click(function(e) {
window.location.hash = $(this).attr("id");
e.preventDefault();
});
$(window).on('hashchange', function() {
if (location.hash === '#hash1') {
$("div.content").html('Hash one added!');
}
if (location.hash === '#hash2') {
$("div.content").html('Hash two added!');
}
if (location.hash === '') {
$("div.content").html('');
}
});
});
</script>
</body>
</html>