Reputation: 5096
I'm trying to make it possible to reach certain tabs in the page by using hash-variables.
It works as intended for:
It does not work when:
test.php
already loaded and manually enter "#tab2" in the address bar (making it test.php#tab2
and 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!
Upvotes: 1
Views: 1003
Reputation: 154818
If the page is loaded and you append #...
to the URL, nothing is executed because you don't trigger the .menu
click handler, and nothing else makes the .showPage
function execute.
You might want to use the hashchange
event of window
instead. That way, whenever the hash changes (link / manually / etc), you can execute .showPage
.
$(window).bind('hashchange', function(){
$(document).showPage(location.hash); // does include the # for the record
});
Upvotes: 3
Reputation: 22933
Yes, you're right implementation of hash changing mechanism differs across browsers. To abstract from the browser you can use this plugin. Actually is't a bit outdated since the most of the modern browsers have support for manual history managment and using the mechanism of states. In couple of words this mechanism allow you to change the url of the page without actually reloading it. You can read more about this technic here
Upvotes: 1