Skip to content

Instantly share code, notes, and snippets.

@matiskay
Created December 16, 2011 17:30
Show Gist options
  • Save matiskay/1487022 to your computer and use it in GitHub Desktop.
Save matiskay/1487022 to your computer and use it in GitHub Desktop.
A jQuery tab plugin

jQuery Tabs

This code is from Javascript Web Applications by Alex MacCaw

I'm modifying the code and using it as a template to make jQuery plugins.

This is nice demonstration of bind and trigger.

TODO

  • Use on instead of delegate.
  • Create a tutorial or screencast using the ideas from this code.
  • Share your ideas with the world!
jQuery.fn.tabs = function(control){
var element = $(this);
control = $(control);
element.delegate('li', 'click', function(e){
e.preventDefault();
// Retrieve tab name
var tabName = $(this).data('tab');
// Fire custom event on tab click
element.trigger('change.tabs', tabName);
});
// Bind to custom event
element.bind('change.tabs', function(e, tabName){
element.find('li').removeClass('active');
element.find('>[data-tab="' + tabName + '"]').addClass('active');
});
// Bind to custom event
element.bind('change.tabs', function(e, tabName){
control.find('>[data-tab]').removeClass('active');
control.find('>[data-tab="' + tabName + '"]').addClass('active');
});
// Activate first tab
var firstName = element.find('li:first').data('tab');
element.trigger('change.tabs', firstName);
return this;
};
<ul id="tabs">
<li data-tab="users">Users</li>
<li data-tab="groups">Groups</li>
</ul>
<div id="tabsContent">
<div data-tab="users"> ... </div>
<div data-tab="groups"> ... </div>
</div>
(function($) {
$("ul#tabs").tabs("#tabContent");
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment