Use location.hash to pre-select a jQuery UI tab

I have noticed quite a few people asking how to set a default tab during page load using the jQuery UI Tabs Widget. My method is as follows…

<script>
$(function(){
 $('#tabs').tabs({
  selected: (location.hash && parseInt(location.hash.substr(1)) != 'NaN') ? parseInt(location.hash.substr(1)) : 0
 });
});
</script>

I am checking the url for a hash value (eg: mypage.htm#3). If one is found and it can be parsed to an integer, it will use that number for the selected tab, otherwise it defaults to zero.

jQuery UI Tabs Widget documentation

If you are not familiar with the short-hand if/else syntax above, here is an example…

variable = (condition) ? true : false;

Written long-hand it would be…

if (condition) {
 variable = true;
} else {
 variable = false;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>