views:

152

answers:

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

+4  A: 

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.

JorenB
Oh Thanks that works perfectly. I'm such a newbie to jquery, it's nice to get some help sometimes :)
Johnny
Hehe, that's what SO is for ;-)
JorenB
A: 

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.

Ionut Staicu
Is it? I thought `live()` is generally a better solution when dealing with multiple items, as it uses event delegation... `live()` only attaches one event, while binding `click()` to x tabs will create x events. Am I right?
JorenB