Johnny
Johnny

Reputation: 217

Unbind a div and then bind it later

$('.tab').click(function() {
    $(this).unbind("click");
    var classy = $(this).attr("class").split(" ").splice(-1);
    var ihtml = $('.content.'+classy).html();
    $('#holder').html(ihtml);
    $('.tab').removeClass('highlight');
    $(this).addClass('highlight');
    $(this).unbind("click");
});

So in this code I have basically, a tabbed interface. When I click the tabs again the information in the #holder disappears. So what I would like to do is unbind clicks whenever the user clicks on the tab, and then bind it when they switch tabs. How can I integrate this into my code?

Thanks.

Upvotes: 2

Views: 1062

Answers (2)

Ionuț Staicu
Ionuț Staicu

Reputation: 22156

also, you can try to use this kind of syntax (which should be faster and more memory&cpu friendly):

$('.tab').click(function () {
    var t = $(this);
    if (t.hasClass('active')) { return false; }
    $('.active').removeClass('active');
    t.addClass('active');
    /* do some stuff here */
    return false;
});

Or even better, to avoid repeating yourself:

$('.tab').click(function () {
    var t = $(this);
    if (!t.hasClass('active')) {
        $('.active').removeClass('active');
        t.addClass('active');
        /* do some stuff here */
    }
    return false;
});

Why is this faster & cpu friendly? Because you bind this only once. When you use live bind method, the browser will listen for any change in the DOM.

Upvotes: 0

JorenB
JorenB

Reputation: 1831

You could try adding a class 'active' when a tab is clicked (generally good practice), then use jQuery's live() to do some fancy stuff...

$('.tab:not(.active)').live('click', function () { 
    $('.tab').removeClass('active');
    $(this).addClass('active');
    ... 
});

I guess that does the trick.

Upvotes: 5

Related Questions