PDA

View Full Version : Using onhashchange for having your menu on each page of your site.



molendijk
11-10-2013, 10:10 PM
Using the onhashchange event in the right way we can add content to a navigation page without leaving it and yet add an entry to the history. This means that there won't be a white flash on page transition (because we don't leave the navigation page) while bookmark functionality is preserved (because onhashchange adds entries to the history, at least, if we use it in the right way). A simple example:

<!--HEAD OF INDEX.HTML -->
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function hash_change()
{$('#import_div').load(location.hash.substring(1,location.hash.length))}
window.onhashchange=hash_change;
window.onload=hash_change; if(window.location.hash=='')window.location.replace('#start.html')
</script>
</head>

<!--BODY OF INDEX.HTML -->
<body>
<!--SIMPLE MENU:-->
<a href="#start.html">Home</a>
<a href="#page2.html">Page 2</a>
<a href="javascript: void(0)" onclick="location='#page3.html'; return false">Page 3</a>

<!-- THE DIV THAT RECEIVES EXTERNAL CONTENT -->
<div id="import_div"></div>
</body>
Demos and explanations here (http://www.let.rug.nl/molendyk/hashchange).

molendijk
11-11-2013, 10:50 PM
I applied the technique described in my first post to cases in which external content is loaded in an iframe. I added some music to show that it continues to play even when we navigate between the pages of the site, see this (http://mesdomaines.nu/eendracht/hashchange_with_iframe). Works well too. Known issues: in IE, the music continues to play as it should except when navigation is done via the back / forward buttons. In Google Chrome, the iframe sometimes takes some time to load.