Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 240
Jackpot Avatar asked Nov 29 '22 02:11

Jackpot


2 Answers

A more elegant way:

$( ".selector" ).accordion({ active: 1 });

Keep in mind that the active property is zero-indexed. 0 represents the first tab. 1 represents the second.

JQuery doc's are excellent

like image 115
tread Avatar answered Dec 05 '22 08:12

tread


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');
});
like image 36
Guillaume Lehezee Avatar answered Dec 05 '22 08:12

Guillaume Lehezee