0

I am working on a project, where I want to show a second tab active on window load, but it always active the first tab.

Here is my script:

<script>
   $(document).ready(function() {
    $('#tabs div').hide();
    $('#tabs div:first').show();
    $('#tabs ul li:first').addClass('active');
    $('#tabs ul li a').click(function() {
        $('#tabs ul li').removeClass('active');
        $(this).parent().addClass('active');
        var currentTab = $(this).attr('href');
        $('#tabs div').hide();
        $(currentTab).show();
        return false;
    });
});
</script>

The problem is, when I write second in place of first it doesn't work.

3
  • Try using $('#tabs ul li').eq(1).addClass('active') instead Commented Aug 18, 2014 at 11:10
  • And also $('#tabs div').eq(1).show(); Commented Aug 18, 2014 at 11:11
  • i tried this, and it works only for tabs, but i also want to show the content under active tab. which doesn't appear Commented Aug 18, 2014 at 11:12

2 Answers 2

1

Instead of using show and hide outside the click handler and repeating the logic, you can trigger the event for a specific a element:

var $a = $('#tabs ul li a').click(function() {
    $('#tabs ul li').removeClass('active');
    $(this).parent().addClass('active');
    var currentTab = $(this).attr('href');
    $('#tabs div').hide();
    $(currentTab).show();
    return false;
});

$a.eq(1).click();
Sign up to request clarification or add additional context in comments.

Comments

0

Use the JQuery eq method, like this:

$(document).ready(function(){
    $('#tabs div').hide();
    $('#tabs div').eq(1).show();
    $('#tabs ul li').eq(1).addClass('active');
});

1 Comment

it works, but only for tabs, i also want to show the content under it. the div i want to show doesn't appear when the current tab is active,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.