Adding Label Renaming to jQuery UI Tabs

Lately I have been playing a lot with jQuery UI and its tab system.  The tab system makes it really very easy to add a tabbed interface to a web site, simulating within a page the behavior offered by browsers and their tabs.  Using the API given, I was able to create tabs within a few minutes, and it offered almost all of the functionality I needed.  One distinct missing feature is the ability to rename a label once it is created.  The ability to rename a tab is useful when the contents of that tab change and the desired behavior is to keep the user up to date on what is inside.

All of the methods accessible in Tabs are accessible via the $(tabs_selector).tabs('command', arguments) structure. The new addition here will be called label.

It is used as:

$(tabsselector).tabs('label', index, newlabel);

Example:

$('#tabsset').tabs('label', 0, 'New Label');

Adding this functionality to the code is pretty straight forward, a development copy of jQuery UI is needed.  As of this writing, I am working off of version 1.7.2. Once the file is unzipped, the change will be to development-bundle/ui/ui.tabs.js. Make a backup of your ui.tabs.js. Open ui.tabs.js in a text editor and find the length function. Copy in the label function from below. Save. Hook up some code that uses it.

    length: function() {
         return this.anchors.length;
    },

    // begin new label code here.
    label: function(index, label) {
        if(index >= this.anchors.length)
            return;

        // copy old values for the URL and class names.
        var url=this.anchors.eq(index).attr('href');
        var classes=this.lis[index].className;

        // make a new list item with the same relevant info -
        //     url, classes, but with updated label.
        var $li = $(this.options.tabTemplate
                   .replace(/#\{href\}/g, url)
                   .replace(/#\{label\}/g, label));
        $li.addClass(classes).data('destroy.tabs', true);

        // do the replacement and remove the extra data
        //     attached to the element elsewhere.
        $(this.lis[index]).replaceWith($li)
                   .removeData('cache.tabs')
                   .removeData('load.tabs');

        // cause DOM events to get updated.
        this._tabify();
    }
    // end new label code here.