Question

$('.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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top