Skip to content

Instantly share code, notes, and snippets.

@RyoSugimoto
Last active August 29, 2015 14:07
Show Gist options
  • Save RyoSugimoto/fc9dc241b0f1d838bfb4 to your computer and use it in GitHub Desktop.
Save RyoSugimoto/fc9dc241b0f1d838bfb4 to your computer and use it in GitHub Desktop.
タブUIを実装するjQueryプラグイン(その1)。
$.fn.tab = function (options) {
options = $.extend({}, {
activeClass: 'is-active',
defaultTab: 0,
onInit: function ($panels, $tabs) {
$.noop();
},
onChange: function ($panels, $panel, $tab) {
$.noop();
}
}, options);
function changeTab ($panels, $tabs, $this) {
var $panel = $this.data('$panel');
if (!$panel) {
return;
}
$panels.hide();
$panel.show();
$tabs.removeClass(options.activeClass);
$this.addClass(options.activeClass);
if (typeof options.onChange === 'function') {
options.onChange($panels, $panel, $this);
}
}
return this.each(function () {
var $this = $(this),
$tabs = $this.find('a'),
$panels = $('');
$tabs.each(function () {
var $this = $(this),
$panel = $($this.attr('href'));
if ($panel.length > 0) {
$this.data('$panel', $panel);
$panels = $panels.add($panel);
} else {
$this.data('$panel', '');
}
});
if (Number(options.defaultTab) >= $tabs.length) {
options.defaultTab = 0;
}
changeTab($panels, $tabs, $tabs.eq(options.defaultTab));
$tabs.on('click', function (e) {
var $this = $(this);
e.preventDefault();
changeTab($panels, $tabs, $this);
});
if (typeof options.onInit === 'function') {
options.onInit($panels, $this);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment