You need to listen to the hashchange
event using jquery to detect when the hash changes, as these changes do not trigger a page load. See this answer for details: On - window.location.hash - Change?
Edit - more info
As the answer in the link above says, this works differently for different browsers, and ultimately you will get the best results from Ben Alman's script (as Joseph also mentions below). But lets break it down.
Here is a simple example that pushes the hash into an h1 tag:
<!DOCTYPE html>
<html>
<head>
<title>Hash Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
function getHash() {
return document.location.hash.substr(1);
}
$(document).ready(function() {
if(document.location.hash != '') {
$('#sectionName').html(getHash());
}
$(window).bind('hashchange', function() {
$('#sectionName').html(getHash());
});
});
</script>
</head>
<body>
<h1 id="sectionName"></h1>
<a href="#1">1</a> <a href="#2">2</a> <a href="#3">3</a>
</body>
</html>
This example will work in most modern browsers, including IE8, with the caveat that just changing the hash in the URL will not create a new history entry in IE. Hash changes caused by user interaction will create history entries just fine.
If you intend to support IE7 and below then the best approach is to use Ben's plugin, which changes our code slightly because instead of using bind
to listen to the event you subscribe to the event function created by the plugin:
<!DOCTYPE html>
<html>
<head>
<title>Hash Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.ba-hashchange.min.js"></script>
<script type="text/javascript">
function getHash() {
return document.location.hash.substr(1);
}
$(document).ready(function() {
$(window).hashchange(function() {
$('#sectionName').html(getHash());
});
//trigger the change for a hash set at page load
if(document.location.hash != '') {
$(window).hashchange();
}
});
</script>
</head>
<body>
<h1 id="sectionName"></h1>
<a href="#1">1</a> <a href="#2">2</a> <a href="#3">3</a>
</body>
</html>