Skip to content

Instantly share code, notes, and snippets.

@aidanlister
Created February 1, 2015 10:27
Embed
What would you like to do?
Remember tab on init
/**
* jQuery Plugin: Sticky Tabs
*
* @author Aidan Lister <aidan@php.net>
* @version 1.2.0
*/
(function ( $ ) {
$.fn.stickyTabs = function( options ) {
var context = this
var settings = $.extend({
getHashCallback: function(hash, btn) { return hash }
}, options );
// Show the tab corresponding with the hash in the URL, or the first tab.
var $initialTab = $('li.active > a', context);
var showTabFromHash = function() {
var hash = window.location.hash;
var $selectedTab = hash ? $('a[href="' + hash + '"]', context) : $initialTab;
$selectedTab.tab('show');
}
// We use pushState if it's available so the page won't jump, otherwise a shim.
var changeHash = function(hash) {
if (history && history.pushState) {
history.pushState(null, null, '#' + hash);
} else {
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
window.location.hash = hash;
document.body.scrollTop = scrollV;
document.body.scrollLeft = scrollH;
}
}
// Set the correct tab when the page loads
showTabFromHash(context)
// Set the correct tab when a user uses their back/forward button
$(window).on('hashchange', showTabFromHash);
// Change the URL when tabs are clicked
$('a', context).on('click', function(e) {
var hash = this.href.split('#')[1];
var adjustedhash = settings.getHashCallback(hash, this);
changeHash(adjustedhash);
});
return this;
};
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment