Brady Dowling
Brady Dowling

Reputation: 5532

Perform action on <div> depending on class

I'd like toggle the class of an element on click but it looks like jQuery only sees what class the element started out as and isn't reading in the change.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(".red").click(function(){
        $(this).addClass("green");
        $(this).removeClass("red");
    });

    $(".green").click(function(){
        $(this).addClass("red");
        $(this).removeClass("green");
    });
});
</script>
<style>
.green {
    color: green;
}
.red {
    color: red;
}
</style>
</head>
<body>

<p class="green">I should toggle red/green</p>

</body>
</html>

How can I properly toggle the class of an element each time it's clicked?

Upvotes: 0

Views: 457

Answers (3)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you need to use toggleClass()

$(document).ready(function(){
    $(".red, .green").on('click',function(){
        $(this).toggleClass("green red");
    });
});

Upvotes: 6

Ankanna
Ankanna

Reputation: 777

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document.body).ready(function(){
    $(document.body).on('click',"button",function(){$(this).toggleClass("red green");})
});
</script>
<style>
.red {
    font-size: 120%;
    background: red;
}
.green{
background:green;
}
</style>
</head>
<body>
<button class = "green">Toggle class "green" for p elements</button>

</body>
</html>

Upvotes: 0

void
void

Reputation: 36703

You need to use .on, as you are modifying the classes dynamically.

$(document).ready(function(){
    $(document).on("click", ".red", function(){
        $(this).addClass("green");
        $(this).removeClass("red");
    });

    $(document).on("click", ".green", function(){
        $(this).addClass("red");
        $(this).removeClass("green");
    });
});

Upvotes: 1

Related Questions