javascriptjquerylistaccordionjquery-tabs

jquery Accordion - how to open the second tab by default on page loading


i'm an absolute noob to jquery and javascript, and really i'm just using a simple code i've found online. This creates an accordion list, but I would like to open the second tab (or any tab other than the first) on page loading. Then, when clicking on any other tab, the tab opened by default should be closed.

This is the code i'm using:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Document</title>

<style>
    .accord-content { display: none; }
</style>
</head>

<body>
    <div class="accordion">
    <div class="accord-header">Header 1</div>
    <div class="accord-content">This is the content for the first header.</div>
    <div class="accord-header">Header 2</div>
    <div class="accord-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
    </div>

</body>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {
    $(".accordion .accord-header").click(function() {
    if($(this).next("div").is(":visible")){
    $(this).next("div").slideUp("slow");
    } else {
    $(".accordion .accord-content").slideUp("slow");
    $(this).next("div").slideToggle("slow");
    }
    });
    });
    </script>
</html>

How can I achieve this? The simplest, the better.

Thanks yo everyone in advance.


Solution

  • You can use the .trigger() to simulate a click on the desired tab. This is a working fiddle.

    On your jquery, before the end of the document.ready :

    $(".accordion .accord-header:eq(1)").trigger('click');
    

    So your final JS :

    $(document).ready(function() {
        $(".accordion .accord-header").click(function() {
            if($(this).next("div").is(":visible")){
                $(this).next("div").slideUp("slow");
            } else {
                $(".accordion .accord-content").slideUp("slow");
                $(this).next("div").slideToggle("slow");
            }
        });
        $(".accordion .accord-header:eq(1)").trigger('click');
    });