Adding jQuery tabs dynamically, or what to do when there is no pre-existing HTML for the tabs

Published on Sunday, 26 April 2009.

UPDATE August 11, 2009: I realized this article had a major flaw: no working code! So I wrote another article and, in addition, you can go directly to the demo.

If you have worked with jQuery for some time, it is most likely that you already heard about jQuery tabs. They are a neat solution to some information display problems (e.g., when you are short on content space). They are pretty easy to install and customize (with the beautiful Theme Roller application). But what happens when you have to create the HTML code on the fly? Meaning, there's no pre-existing HTML structure for you to attach the tabs.

I resolved this situation by doing the following (of course, there must be better ways but I couldn't find them at the internets):

Add HTML content dynamically to be able to add tabs programmatically:

    var create_ui = function (tabs) {
        var dom = $.DIV({},
            $.H1({}, 'Whatever just for demonstration purposes', $.SPAN({}, 'version 1.0')),
            $.DIV({id: tabs}, '')
        );
        $('body').append(dom);  
    };

Initialize the tabs, and then remove the dummy empty tab:

    var setup_tabs = function (tabs_id) {
        var dom = $.UL({},
            $.LI({}, 
                $.A({href:'#dummy'}, '')
            )
        );
        $(tabs_id).append(dom);

        // this boilerplate code that can be helpful, otherwise remove it
        $(tabs_id).tabs({
            select: function (event, ui) {
            },
            remove: function (event, ui) {
            },
            show: function (event, ui) {
                if (ui.panel) {
                    console.log(ui.panel.id);
                }
            }
        });

        // remove the dummy tab
        $(tabs_id).tabs('remove', 0);
    };

And now you can add tabs programmatically:

    var tabs_id = '#my_tabs';
    var add_tab = function (id, name, data) {
        $(tabs_id).append(data).tabs('add', id, name);
    };

I'm using the jQuery DOM plugin to create HTML quickly. Most of the time, this is not a good idea, specially, for complex interfaces. Think about maintainability ;).

Happy hacking! =)