Reputation: 95
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
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
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
Reputation: 1263
$("#item").click(function()
{
if($(".menu").hasClass("active"))
{
$(".menu").removeClass("active");
$(".footer").addClass("status");
}
else
{
$(".menu").addClass("active");
$(".footer").removeClass("status");
}
});
Upvotes: 0
Reputation: 690
$("#item").click(function() {
if(!$(".menu").hasClass("active")){
$(".menu").addClass("active");
$(".footer").removeClass("status");
}else{
$(".menu").removeClass("active");
$(".footer").addClass("status");
}
});
Upvotes: 2
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