开发者

Automatically showing 1 part of jquery accordion on page load instead of initially hiding all parts

I have the following Javascript code which controls an accordion type set of divs. The set of divs is built this way:

<h1>click here to show next div</h1>
<div>text to show</div>
<h1>click here to show next div</h1>
<div>text to show</div>
<h1>click here to show next div</h1>
<div>text to show</div>

I assume you all know how an accordion works. H1 tag is the trigger onclick which shows the next div but hides all other divs.

<script language="javascript"><!--
$(document).ready(function(){
  toggler();
});
function toggler() {

$('.trigger').click( function() {
    if ( $(this).hasClass('trigger_active') ) {
        $(this).next('.toggle_container').slideToggle('fast');
        $(this).removeClass('trigger_active');
    } else {
        $('.trigger_active').next('.toggle_container').slideToggle('fast');
        $('.trigger_active').removeClass('trigger_active');
        $(this).next('.toggle_container').slideToggle('fast');
        $(this).addClass('trigger_active');
    };
return false;
});
}
//--></script>

Now on page load all divs will be closed, which is kind of stupid. What I want to do now is have the first div being act开发者_高级运维ivated on page load, so the user doesn't have to click on it. You have any idea how to do this? I tried to give the first div a unique ID and show() it on load of DOM, but then it won't collapse if I click on other triggers (it will never hide)


You can trigger an actual click for the first on load:

$(function() {
    // ...
    $('.trigger:first').click();
}

However, in your HTML there are no .triggers, is that correct?


Mimicking a click event on page load doesn't feel clean to me. You might need just to assign the classes for your first items. Check this jsFiddle for an example.


You can call click function of the .trigger on page load method

$(document).ready(function(){
  toggler();
 $('.trigger:first').click();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜