thibaultlgd
thibaultlgd

Reputation: 65

first click on accordion not working

my accordion is not working properly.

on the first time you click, the content is ont displaying . . . .

otherwise if you click the second time and after it does appear . .

Any help will be brilliant,

Here is my fiddle:

https://jsfiddle.net/ugddnof4/

All the thtml is there.

OR below is my js:

(function($) { $('.accordion > li:eq(0) a').addClass('active').next().slideDown();

$('.accordion a').click(function(j) {
    var dropDown = $(this).closest('li').find('ul.accordion-content li, p, ul.accordion-content');

    $(this).closest('.accordion').find('ul.accordion-content li, p, ul.accordion-content').not(dropDown).slideUp();

    if ($(this).hasClass('active')) {
        $(this).removeClass('active');
    } else {
        $(this).closest('.accordion').find('a.active').removeClass('active');
        $(this).addClass('active');
    }

    dropDown.stop(false, true).slideToggle();

    j.preventDefault();
});
 })(jQuery);

thanks a lot for all your time!

Upvotes: 0

Views: 1586

Answers (1)

Chris Lear
Chris Lear

Reputation: 6742

This seems to work

https://jsfiddle.net/9erfLokh/1/

New js:

(function($) {
    $('.accordion > li:eq(0) a').addClass('active').next().slideDown();

    $('.accordion a').click(function(j) {
        var dropDown = $(this).closest('li').find('ul.accordion-content');
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).closest('.accordion').find('a.active').closest('li').find('ul.accordion-content').slideUp();
            $(this).closest('.accordion').find('a.active').removeClass('active');
            $(this).addClass('active');
        }

        dropDown.stop(false, true).slideToggle();

        j.preventDefault();
    });
})(jQuery);

I think your problem was mainly that dropDown was returning a whole set of dom objects, and you were running slideToggle on all of them. This version will only close a block if there is one active, and will always toggle the clicked one, but takes care to only run slideToggle on a single element.

Upvotes: 1

Related Questions