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.
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
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');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With