Cartoon
Cartoon

Reputation: 111

Toggle Class not Working

I'm using a button to change the color of another button when user clicks on it. But, due to some unknown reasons it's not working. Please, help me out here.

<!DOCTYPE html>
<html>
<head>
    <title>My Gallery</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/custom.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <p id="btn1" class="btn btn-primary">Click me!</p>
        <p id="btn2" class="btn btn-default">Change color!</p>
    </div>

    <!-- Javascript -->
    <script src="js/jquery-2.1.3.js"></script>
    <script src="js/bootstrap.min.js"></script>

    <script>
        var main = function() {
            $("#btn2".click(function() {
                $("#btn1").toggleClass(".btn-primary");
            });
        }

        $(document).ready(main);
    </script>
</body>
</html>

Upvotes: 2

Views: 5189

Answers (3)

Paul Radich
Paul Radich

Reputation: 715

Should look like this.

$("#btn2").click(function() {
    $("#btn1").toggleClass("btn-primary");
});

Upvotes: 1

Jonathan Wood
Jonathan Wood

Reputation: 67193

This:

$("#btn2".click(function() {

Should be:

$("#btn2").click(function() {

Notice the closing parenthesis after your "#btn2" selector.

As others have pointed out, you also need to remove the period from the start of the class name being toggled. You need to check your console for errors.

Upvotes: 1

Igor
Igor

Reputation: 15893

do not put "." in front of the class name (as you would do in selector):

$("#btn1").toggleClass("btn-primary");

Upvotes: 3

Related Questions