I’m trying to make it possible to reach certain tabs in the page by using hash-variables.
It works as intended for:
- Links within the page
- Opening a new browser window/tab with the adress (test.php#tab2)
It does not work when:
- When you have
test.phpalready loaded and manually enter “#tab2” in the address bar (making ittest.php#tab2and finishing off with enter). The page does not load and the script is not run.
I’ve tried it in different browsers and the result is more or less the same. In Chrome you can select the whole url in the address bar and then press enter (again), that works – but in general it’s the same issue there.
I’ve taken the script out of my page and made a small template, the full code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-language" content="en" />
<script type="text/javascript" src="inc/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.fn.showPage = function(hash) {
if (hash === '#tab1' || hash === '') {
if ($('#tab1').is(':hidden')) {
$('#tab1').show();
$('#tab2, #tab3').hide();
}
} else if (hash === '#tab2') {
if ($('#tab2').is(':hidden')) {
$('#tab2').show();
$('#tab1, #tab3').hide();
}
} else if (hash === '#tab3') {
if ($('#tab3').is(':hidden')) {
$('#tab3').show();
$('#tab1, #tab2').hide();
}
}
}
$('.menu').click(function(e){
e.preventDefault();
var hash = $(this).attr('id');
window.location.href = 'test.php' + hash;
$(document).showPage(hash);
});
var hash = location.hash;
$(document).showPage(hash);
});
</script>
</head>
<body>
<a href="#" id="#tab1" class="menu">Tab 1</a> <a href="#" id="#tab2" class="menu">Tab 2</a> <a href="#" id="#tab3" class="menu">Tab 3</a>
<div id="tab1">
Tab 1
</div>
<div id="tab2" style="display:none;">
Tab 2
</div>
<div id="tab3" style="display:none;">
Tab 3
</div>
</body>
</html>
I hope I’ve made myself clear enough. Appreciate any feedback!
If the page is loaded and you append
#...to the URL, nothing is executed because you don’t trigger the.menuclick handler, and nothing else makes the.showPagefunction execute.You might want to use the
hashchangeevent ofwindowinstead. That way, whenever the hash changes (link / manually / etc), you can execute.showPage.http://jsfiddle.net/yJTJz/