Question

I have created a Javascript toggle menu:

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");

        } else {
            $('.toggle').next().slideUp("fast").removeClass("expanded");
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

When I click on another item in the menu, the class "expanded" is not removed from the other elements. I've tried many different things but can't get my head around it. Any help would be appreciated.

Was it helpful?

Solution

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");
            $(this).addClass('collapsed');
            $(this).removeClass('expanded');
        } else {
            var $expandedItems = $('.expanded');
            $expandedItems.next().slideUp("fast")
            $expandedItems.addClass('collapsed');
            $expandedItems.removeClass('expanded');
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

Based on your comments I think you are after something like this.

OTHER TIPS

$(document).ready(function() {
    $('.toggle').click(function () {
        if ($(this).hasClass("expanded")) {
            $(this).next().slideUp("fast");

        } else {
            $('.expanded').removeClass('expanded');//here is your problem
            $(this).next().slideDown("fast");
            $(this).removeClass("collapsed");
            $(this).addClass("expanded");
        }
    });
});

This should be remove expanded class from your jquery code

Note Tested although please tell me if its not working

updated

Demo

And for jquery i think you are missing too much information here check demo here Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top