user3192978
user3192978

Reputation: 95

Toggle with a click function

I have a small click function inside my website

$("#item").click(function() {
    $(".menu").addClass("active");
    $(".footer").removeClass("status");
});

Now when a user clicks on the #item - everything works, but now I would like to have the ability to inverse that, when the user clicks again on it, like so:

$(".menu").removeClass("active");
$(".footer").addClass("status");

And the user can click as much as he likes to do so. How is this possible? I tried it with another click() inside the first click() but then it only works one time.

Upvotes: 0

Views: 75

Answers (5)

Vytalyi
Vytalyi

Reputation: 1695

I would do it like this:

$("#item").click(function() {
    var menu = $(".menu")
        , footer = $(".footer");

    if (menu.hasClass("active") && !footer.hasClass("status")) {
        menu.removeClass("active");
        footer.addClass("status");
    }
    else {
        menu.addClass("active");
        footer.removeClass("status");
    }
});

Upvotes: 0

Irvin Dominin
Irvin Dominin

Reputation: 30993

You can use toggleClass.

Ref:

Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.

Code:

$("#item").click(function() {
    $(".menu").toggleClass("active");
    $(".footer").toggleClass("status");
});

Upvotes: 2

hayj
hayj

Reputation: 1263

$("#item").click(function()
{
    if($(".menu").hasClass("active"))
    {
        $(".menu").removeClass("active");
        $(".footer").addClass("status");
    }
    else
    {
        $(".menu").addClass("active");
        $(".footer").removeClass("status");
    }
});

Upvotes: 0

TriniBoy
TriniBoy

Reputation: 690

$("#item").click(function() {
    if(!$(".menu").hasClass("active")){
        $(".menu").addClass("active");
        $(".footer").removeClass("status");
    }else{
        $(".menu").removeClass("active");
        $(".footer").addClass("status");
    }
});

Upvotes: 2

Shovan
Shovan

Reputation: 215

This code may work

$("#item").click(function() {
       $(".menu").toggleClass("active");
       $(".footer").toggleClass("status");
});

but make sure you have correct classes applied before click event is fired.

Upvotes: 0

Related Questions