0

In the example below, I want to change pad's color via JS to green, but also make it transition to yellow when it is active.

However, changing the color via JS like this: pad.style.background = 'green' will make the transition stop working. If I remove this line, the transition will work fine.

Why is that so and how can I fix this?

let pad = document.getElementsByClassName('pad')[0]
pad.style.background = 'green'
.pad{
  width: 80px;
  height: 80px;
  background: black;
  transition: background .5s;
}
.pad:active {
  background: yellow;
}
<!DOCTYPE HTML>
    <body>
        <div class="pad"></div>
    </body>
barciewicz
  • 3,511
  • 6
  • 32
  • 72
  • use !important. https://stackoverflow.com/questions/9245353/what-does-important-mean-in-css – kevin Jul 18 '19 at 19:55

3 Answers3

1

It seems like JS is adding green to the :active state too. Add !important to the active style in your css to make it more of a priority:

.pad:active {
    background: yellow!important;
}
Kyle
  • 302
  • 2
  • 5
  • Actually when you style with js it put it inline so it override the css. But your solution with the !important will do the job. – A. Meshu Jul 18 '19 at 20:01
  • This will fix the problem, but using !important is generally undesirable because it makes it almost impossible to override that rule. It's better to add a `green` class style and use JS to add `green` to the classlist, as in the other solutions. – Benjamin Jul 18 '19 at 20:05
1

The reason for not working is because pad.style.background will add an inline css style which has a priority over a css class

Solution:

use a class instead of inline style like in the code bellow:

let pad = document.getElementsByClassName('pad')[0]
pad.classList.add("green");
.pad {
  width: 80px;
  height: 80px;
  background: black;
  transition: background .5s;
}

.pad.green {
  background: green;
}

.pad:active {
  background: yellow;
}
<div class="pad"></div>
Chiller
  • 9,520
  • 2
  • 28
  • 38
1

This is happening because you're overriding the existing style by applying the style via style attribute on the HTML element.

Instead you should create a new class and apply that using JavaScript, in that case the original styles won't be overidden and the transition would still work

Have your CSS as:

    .pad {
      width: 80px;
      height: 80px;
      background: black;
      transition: background .5s;
    }
    .pad:active {
      background: yellow;
    }

    .pad-green {
      background: green;
    }

And then in your JavaScript, do this:

let pad = document.getElementsByClassName('pad')[0]
pad.classList.add('pad-green')

Hope that helps, let me know in the comments if there are any questions.

Umer Hassan
  • 1,119
  • 6
  • 16
  • 23