Potterapple Potterapple - 3 months ago 12
CSS Question

How to change color of button in active state using inline CSS?

Is there any way to change the background color and/or border color of a button when it is in active state (i.e. Clicked) using inline css?

<button class="btn btn-xs btn-primary btn-inverse dropdown-toggle" type="button" data-toggle="dropdown" style="margin-top: 12px; background-color: rgba(0, 0, 0, 0); border-color:rgba(0, 0, 0, 0); margin-right:20px">

Something like this but for when the button is clicked?


Considering that css :active is just a css pseudo-class and not a Dom property or attribute you can't have an inline equivalent for that.

But, if in your case, the click event could be a valid alternative, you can do something like that...

  function toggleBg(element, color) {
    if(!color) {
      color = element.dataset.normalColor;
    } else {
      element.dataset.normalColor = element.style.backgroundColor;

    element.style.backgroundColor = color;

<button onmousedown="toggleBg(this,'red')" onmouseup="toggleBg(this)">RED ON PRESS</button>

Just a note, inline-styling or inline-javascript isn't a good practice, if you can, use css:

  button:active { background: red; }

<button>RED WHEN ACTIVE</button>