Add close button to dynamically added jQuery UI tabs

When working with jQuery UI tabs it is really easy to dynamically add tabs. You just use tabs  ”add” method as specified in the documentation: .tabs( ‘add’ , url , label , [index] ). But there is no method for dynamically adding a close button so the tabs can be removed. Here is a quick little script I wrote to do just that.

$(function() {
		//DECLARE FUNCTION: removetab
		var removetab = function(tabselector, index) {
			$(".removetab").click(function(){
				$(tabselector).tabs('remove',index);
			});
		 };

		//create tabs
		$("#tabs").tabs({
		   add: function(event, ui) {
		   		//select newely opened tab
				$(this).tabs('select',ui.index);
				//load function to close tab
				removetab($(this), ui.index);
		   },
		   show: function(event, ui) {
		   		//load function to close selected tabs
				removetab($(this), ui.index);
		   }
		});

		//load new tab
		$(".addtab").click(function(){
			var href=$(this).attr("href");
			var title=$(this).attr("title");
			$("#tabs").tabs( 'add' , href , title+'  ');
			return false;
		});

	});

Usage is simple. Just add class “.addtab” to the links you want opened in a tab, and make sure the link has “title” attribute set as it is used for the tab label.

Add Tab

Improvements

To avoid adding of duplicate tabs. a function should be added that checks if a specific tab was already added. It should be easy to do once I find time to do it :)

Update: 02/26/2010

If you don’t want to use jQuery UI, but would like to achieve similar effect, visit JankoAtWarpSpeed.com.

Related Posts: