0

I'm working on a simple project where I want to animate a div element. I'm trying to make a white box both move to the right and change color when it's clicked. I'm using a JavaScript click event to toggle a CSS class.

The problem is that my code only makes the box move, but it does not change its color. I have a transition: all property on the box, so I expected it to animate both properties.

Here is my code:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Animation Problem</title>
    <style>
        body {
            display: flex;
            justify-content: center;
        }
        #container {
            height: 130px;
            width: 350px;
            background: linear-gradient(to right, red, blue);
            display: flex;
            align-items: center;
            border-radius: 100px;
        }
        #box {
            height: 100px;
            width: 100px;
            background-color: #edeaea;
            margin-left: 15px;
            cursor: pointer;
            border-radius: 50%;
            transition: all 1s ease-in-out;
        }
        .clicked-box {
            transform: translateX(220px);
        }
    </style>
</head>
<body>
    <div id="container">
        <div id="box"></div>
    </div>
    <script>
        let box = document.querySelector("#box");
        box.addEventListener("click", function(){
            box.classList.toggle('clicked-box');
        });
    </script>
</body>
</html>```




I have tried adding background-color: blue; to the .clicked-box class, but it still doesn't seem to work, and I'm not sure if I'm missing a property or using the transition incorrectly.

How can I get the box to both move and change color smoothly when it's clicked?

`your text`
3
  • What kind of color change are you expecting to happen when you add the class? Commented Sep 15 at 19:00
  • Please elaborate on "it still doesn't seem to work"; does it do anything? If so, what? Compare that to your expectation. Commented Sep 15 at 19:04
  • 2
    Look carefully at the specificities in your stylesheet. #box is higher than .clicked-box. See developer.mozilla.org/en-US/docs/Web/CSS/CSS_cascade/… Commented Sep 15 at 20:03

1 Answer 1

1

You need to change your css as below to see the color change

.clicked-box {
            transform: translateX(220px);
            background-color: green !important;
        }
or (better)

#box.clicked-box {
            transform: translateX(220px);
            background-color: green;
        }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.