Skip to content

Instantly share code, notes, and snippets.

@FZambia
Last active December 15, 2015 06:49
Show Gist options
  • Save FZambia/5219425 to your computer and use it in GitHub Desktop.
Save FZambia/5219425 to your computer and use it in GitHub Desktop.
Twitter bootstrap tab's jQuery plugin to show hash in location string (custom prefix prevent page jumps to links containing hash), keep current tab on page reload and react on hash change event
/*
Usage:
$(document).ready(function() {
$('#tabs').prefix_tab({
prefix: 'settings_',
default_route: 'general'
});
});
*/
;(function($) {
$.fn.extend({
prefix_tab : function(custom_options) {
var defaults,
options,
show_tab,
initialize;
defaults = {
sep: '/',
prefix: "tab_",
default_route: null
};
options = $.extend(defaults, custom_options);
show_tab = function(tabs) {
var hash = document.location.hash;
if (hash) {
tabs.find('a[href='+hash.replace(options.sep + options.prefix,"")+']').tab('show');
} else {
if (options.default_route) {
window.location.hash = options.sep + options.prefix + options.default_route;
}
}
};
initialize = function(tabs) {
show_tab(tabs);
tabs.on('shown', 'a', function (e) {
window.location.hash = e.target.hash.replace("#", "#" + options.sep + options.prefix);
});
if ("onhashchange" in window) {
var hash_changed = function() {
show_tab(tabs);
};
window.onhashchange = hash_changed;
}
};
return $(this).each(function(){
var tabs = $(this);
initialize(tabs);
});
}
})
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment