RyoSugimoto
10/8/2014 - 11:48 AM

タブUIを実装するjQueryプラグイン(その1)。

タブ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);
		}
	});
};