문제

For the purpose of a mobile navigation button, i want the link to click (show menu) add active class and then, when you click the SAME link again (collapse menu) it removes the class.

$(function() {  
    $(".nav-mobile").click(function () {
        $(".nav-mobile").removeClass("active");
        $(this).addClass("active");
    });
});

This adds the active class on click, but doesn’t remove it when clicked again.

Is it possible to remove it?

도움이 되었습니까?

해결책

You can use the toggleClass() function in jQuery. It does exactly what you want.

Check the api doc: https://api.jquery.com/toggleClass/

다른 팁

Use this code instead :

$(function() {  
    $(".nav-mobile").click(function () {
        $(".nav-mobile").not(this).removeClass("active");
        $(this).toggleClass("active");
    });
});

Try this

$(function() {
    $(".nav-mobile").click(function () {
        var $this = $(this);
        if( $this.hasClass('active')) {
            $this.removeClass('active');
        } else {
            $(".nav-mobile").removeClass("active");
            $this.addClass("active");
        }
    });
});
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top