eXorcist
eXorcist

Reputation: 69

jQuery Toggle First Opened

I want to make first toggle opened on page load by adding an extra class to toggle's container. How can I do it?

This is my toggle's script: http://jsfiddle.net/gKAFT/

$(".toggle-container").hide();
$(".trigger").toggle(function(){
    $(this).addClass("active");
    }, function () {
    $(this).removeClass("active");
});
$(".trigger").click(function(){
    $(this).next(".toggle-container").slideToggle();
});

Greetings.

Upvotes: 0

Views: 3453

Answers (4)

Ram
Ram

Reputation: 144659

You can trigger the event:

$(".trigger").click(function(){
    $(this).next(".toggle-container").slideToggle();
}).first().click();

http://jsfiddle.net/sAxC7/

Note that toggle method is deprecated, you can use toggleClass instead:

$(".trigger").click(function(){
    $(this).toggleClass('active').next(".toggle-container").slideToggle();
}).first().click();

http://jsfiddle.net/B3Luc/

Upvotes: 1

Talha Akbar
Talha Akbar

Reputation: 10030

$(".trigger:first").trigger("click");

Upvotes: 0

Minko Gechev
Minko Gechev

Reputation: 25682

You can use this solution:

jQuery(document).ready(function($) {       

    $(".toggle-container").hide(); 
    $(".trigger").toggle(function(){
        $(this).addClass("active");
        }, function () {
        $(this).removeClass("active");
    });
    $(".trigger").click(function(){
        $(this).next(".toggle-container").slideToggle();
    });

    $('.toggle-container').first().show(); 
});
​

Here is a fiddle. The thing that's different is the last line $('.toggle-container').first().show(); which shows the first toggle container.

Upvotes: 1

Stefan
Stefan

Reputation: 14863

Use the fist selector:

$(".trigger:first").next(".toggle-container").slideToggle();

Fiddler: http://jsfiddle.net/cXhQN/

However this doesn't work for SEO since Search engindes don't execute the JavaScript.

Upvotes: 1

Related Questions