Last active
August 29, 2015 13:57
-
-
Save davist11/9474299 to your computer and use it in GitHub Desktop.
jQuery tabs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @name jQuery Tabs | |
* @author Trevor Davis | |
* @copyright (cc) Trevor Davis (http://www.viget.com) | |
* | |
* Licensed under the CC-GNU GPL (http://creativecommons.org/licenses/GPL/2.0/) | |
*/ | |
;(function($, window, document, undefined) { | |
var Tabs = function(elem, options) { | |
this.elem = elem; | |
this.$elem = $(elem); | |
this.options = options; | |
this.metadata = this.$elem.data('tabs-options'); | |
this.$navTabs = this.$elem.find('.tabs__nav'); | |
this.$tabsContainer = this.$elem.find('.tabs__items'); | |
this.$tabs = this.$tabsContainer.find('.tabs__tab'); | |
}; | |
Tabs.prototype = { | |
defaults: { | |
currentClass: 'current' | |
}, | |
init: function() { | |
//Merge options | |
this.config = $.extend({}, this.defaults, this.options, this.metadata); | |
//Handle Mouseover | |
this.$navTabs.on('click.tabs', 'a', this.handleClick.bind(this)); | |
//Make tabs linkable via a url hash | |
this.setInitial(); | |
return this; | |
}, | |
changeTabs: function($parent, $target) { | |
this.$navTabs.find('.' + this.config.currentClass).removeClass(this.config.currentClass); | |
$parent.addClass(this.config.currentClass); | |
this.$tabsContainer.find('.' + this.config.currentClass).removeClass(this.config.currentClass); | |
$target.addClass(this.config.currentClass); | |
}, | |
handleClick: function(e) { | |
e.preventDefault(); | |
var $this = $(e.currentTarget); | |
var $parent = $this.parent(); | |
var target = $this.attr('href').split('#')[1]; | |
var $target = $('#' + target); | |
if ($target && !$parent.hasClass('current')) { | |
this.changeTabs($parent, $target); | |
} | |
}, | |
setInitial: function() { | |
var hash = window.location.href.split('#')[1]; | |
var cleanHash; | |
var $target; | |
var $parent; | |
if (hash) { | |
cleanHash = hash.replace('tab-', ''); | |
$target = this.$tabsContainer.find('#' + cleanHash); | |
if ($target.length) { | |
$parent = this.$navTabs.find('a[href$="#' + cleanHash + '"]').parent(); | |
if ($parent.length) { | |
this.changeTabs($parent, $target); | |
} | |
} | |
} | |
} | |
}; | |
Tabs.defaults = Tabs.prototype.defaults; | |
$.fn.tabs = function(options) { | |
return this.each(function() { | |
new Tabs(this, options).init(); | |
}); | |
}; | |
})(jQuery, window , document); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment