You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.3 KiB

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