tags:

views:

23

answers:

2

Hi,

how can i activate the second tab of my web page in page load , i have done the tabs using jquery and ul.

below is the codes

<div class="tabcontainer">
  <ul class="tabs">
    <li><a href="#tab1">Saved Recipes</a></li>
    <li><a href="#tab2">Groups</a></li>
    <li><a href="#tab3">Friends</a></li>
    <li><a href="#tab4">My Recipes</a></li>
  </ul>
</div>

<div class="tab_container">
<!-- Tab 1 Starts Here  -->
  <div id="tab1" class="tab_content"></div>    
  <div id="tab2" class="tab_content"></div>
  <div id="tab3" class="tab_content"></div>    
  <div id="tab4" class="tab_content"></div>    
</div>

Script:

$(document).ready(function() {
    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content

    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });
});

I know how to activate first and last one, but how can i activate the second and third one during page load.

please help...

A: 

You can use .eq() for example:

var activeTab = 1; //0 based, so 1 = 2nd
$("ul.tabs li").eq(activeTab).addClass("active").show();
$(".tab_content").eq(activeTab).show();

Or :eq() like this:

$("ul.tabs li:eq(1)").addClass("active").show();
$(".tab_content:eq(1)").show();

Or...what I'd do is use the click handler you already have, no need to duplicate code, like this:

$(function() {
  $(".tab_content").hide(); //Hide all content

  $("ul.tabs li").click(function() {
    $(this).addClass("active").siblings().removeClass("active");
    var activeTab = $(this).find("a").attr("href");
    $(activeTab).fadeIn().siblings().hide();
    return false;
  }).eq(1).click(); //click the second
});

Or if you have styling control, make the <a> take up the entire <li> and attach the click handler to the anchor directly:

$(function() {
  $(".tab_content").hide();

  $("ul.tabs li a").click(function(e) {
    $(this).closest("li").addClass("active").siblings().removeClass("active");
    $(this.hash).fadeIn().siblings().hide();
    e.preventDefault();
  }).eq(1).click(); //click the second
});
Nick Craver
thanks guys for your help
tibin mathew
+1  A: 

Use a jQuery selector that matches the hash, and click it:

$('.tabs li a[href=\#tab2]').click();
Tomas Lycken
`<tabs>` isn't a valid element :)
Nick Craver
@Nick - It should have been `.tabs` in the selector, obviously. Thanks for pointing it out!
Tomas Lycken