I’m using page-anchors to direct users to particular tabs from a menu. However when you’re on the page with the tabs clicking the link doesn’t redirect. It simply changes the hash in the URL. Any idea how I could resolve this?
example link
This is on WordPress btw.
jQuery(document).ready(function($){
$(function() {
$( "#tabs" ).tabs();
if(document.location.hash!='') {
//get the index from URL hash
tabSelect = document.location.hash.substr(1,document.location.hash.length);
$("#tabs").tabs('select',tabSelect-1);
}
});
});
You need to listen to the
hashchangeevent 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:
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
bindto listen to the event you subscribe to the event function created by the plugin: