views:

59

answers:

3

I have a group of tabs that have hidden content which display when the tab is clicked. The jQuery looks like this:

jQuery(document).ready(function($){
 var sections = $('.section').hide();

 $('.tablink').click(function(e){
        e.preventDefault();
        sections.hide();
        $($(this).attr('href')).show();
        $(this).closest('ul').find('li').removeClass('active');
        $(this).closest('li').addClass('active');
 });

 var tab = getParameterByName('tab');
 if(tab)
    $('.tablink:eq('+(tab-1)+')').click();
 else
     $('#section1').show();  //show first section
});

The HTML looks like this:

  <li id="tab1" class="active"><a class="tablink" href="#section1">Link1</a></li>
  <li id="tab2"><a class="tablink" href="#section2">Link2</a></li>
  <li id="tab3"><a class="tablink" href="#section3">Link3</a></li>

I'm trying to figure out how to add an additional function to the tab click that says:

if #tab2 has the class .active then do X.

This seems very straight forward, but I can't get it. Ideas?

+4  A: 

You can do it using .length to see how many elements the selector found like this:

if($('#tab2.active').length === 1) {
  //do something, it has the class
}
Nick Craver
+1 Overall, I'd personally use this solution over mine, although I'd ditch the `=== 1`.
patrick dw
+3  A: 

if #tab2 has the class .active then do X.

You mean this:

if ($('#tab2').hasClass('active')){
  // your code..
}
Sarfraz
+1  A: 

In addition to the solutions provided, you could do this:

if ($('#tab2').is('.active')){
  // it was .active
}

Not as fast as .length, but is easy to read and understand.

patrick dw
It is crazy expensive in comparison though :)
Nick Craver
@Nick - See my update.
patrick dw