| 1 |
/** |
| 2 |
* jQuery Plugin: Sticky Tabs |
| 3 |
* |
| 4 |
* @author Aidan Lister <[email protected]> |
| 5 |
* @version 1.2.0 |
| 6 |
*/ |
| 7 |
(function ( $ ) { |
| 8 |
$.fn.stickyTabs = function( options ) { |
| 9 |
var context = this |
| 10 |
|
| 11 |
var settings = $.extend({ |
| 12 |
getHashCallback: function(hash, btn) { return hash }, |
| 13 |
selectorAttribute: "href", |
| 14 |
backToTop: false, |
| 15 |
initialTab: $('li.active > a', context) |
| 16 |
}, options ); |
| 17 |
|
| 18 |
// Show the tab corresponding with the hash in the URL, or the first tab. |
| 19 |
var showTabFromHash = function() { |
| 20 |
var hash = settings.selectorAttribute == "href" ? window.location.hash : window.location.hash.substring(1); |
| 21 |
var selector = hash ? 'a[' + settings.selectorAttribute +'="' + hash + '"]' : settings.initialTab; |
| 22 |
$(selector, context).tab('show'); |
| 23 |
setTimeout(backToTop, 1); |
| 24 |
} |
| 25 |
|
| 26 |
// We use pushState if it's available so the page won't jump, otherwise a shim. |
| 27 |
var changeHash = function(hash) { |
| 28 |
if (history && history.pushState) { |
| 29 |
history.pushState(null, null, window.location.pathname + window.location.search + '#' + hash); |
| 30 |
} else { |
| 31 |
scrollV = document.body.scrollTop; |
| 32 |
scrollH = document.body.scrollLeft; |
| 33 |
window.location.hash = hash; |
| 34 |
document.body.scrollTop = scrollV; |
| 35 |
document.body.scrollLeft = scrollH; |
| 36 |
} |
| 37 |
} |
| 38 |
|
| 39 |
var backToTop = function() { |
| 40 |
if (settings.backToTop === true) { |
| 41 |
window.scrollTo(0, 0); |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
// Set the correct tab when the page loads |
| 46 |
showTabFromHash(); |
| 47 |
|
| 48 |
// Set the correct tab when a user uses their back/forward button |
| 49 |
$(window).on('hashchange', showTabFromHash); |
| 50 |
|
| 51 |
// Change the URL when tabs are clicked |
| 52 |
$('a', context).on('click', function(e) { |
| 53 |
var hash = this.href.split('#')[1]; |
| 54 |
var adjustedhash = settings.getHashCallback(hash, this); |
| 55 |
changeHash(adjustedhash); |
| 56 |
setTimeout(backToTop, 1); |
| 57 |
}); |
| 58 |
|
| 59 |
return this; |
| 60 |
}; |
| 61 |
}( jQuery )); |