dbaugh
dbaugh

Reputation: 746

Optimizing jQuery for Tabs

I am in the process of developing a widget. The widget has three tabs that are implemented in the following way.

<div id="widget">
    <ul id="tabs">
        <li><a href="http...">One</a></li>
        <li><a href="http...">Two</a></li>
        <li><a href="http...">Three</a></li>
    </ul>

    <div id="tab_container">
        <div id="tab_content">
            //Tab Content goes here...
        </div>
    </div>
</div>

// The active class is initialized when the document loads 
$("#tabs li a").click(function()
{
$("#tabs li.active").removeClass("active");
    $("#tab_content").load($(this).attr('href'));
    $(this).parent().addClass("active");

    return false;   
});

The problem I am having is that the jquery code that have written is very slow. If the user changes tabs quickly the widget gets behing and bogged down. This causes the tabs to to not align with the data being displayed and just general lag. I believe that this is because the tab is being changed before $.load() is finished. I have tried to implement the following:

("#tabs li a").click(function()
{
$("#tabs li.active").removeClass("active");
    $("#tab_content").load($(this).attr('href'), function (){
        $(this).parent().addClass("active");
    });

    return false;   
});

It is my understanding that the callback function within in the load function does not execute until the load function is completed. I think this would solve my problem, however I can not come up with a way to select the correct tab that was clicked within the callback function. If this is not the way to do this then what is the best way implement these tabs so that they would stop loading an old request and load the newest tab selection by the user?

Thanks

Upvotes: 0

Views: 194

Answers (2)

Simen Echholt
Simen Echholt

Reputation: 11293

Regardless of whether you should use the jQuery UI tabs or not, this is how your code could be made to work

$("#tabs li a").click(function(e)
{
    var fn = function(a) {
        return function() {
            $(a).parent().addClass("active");
        };
    }
    $("#tabs li.active").removeClass("active");
    $("#tab_content").load($(this).attr('href'), fn(this));

    return false;
});

Upvotes: 1

Chris Johnston
Chris Johnston

Reputation: 1919

Why not just use the jQuery UI Tabs plug-in?

Upvotes: 2

Related Questions