Home > Back-end >  Change color of all clicked buttons
Change color of all clicked buttons

Time:04-19

I have a set of buttons in an html page of the following form:

<button
      id="testID"
      mat-mini-fab
      ngClass="list-button"
      (click)="onClick($event)"
    >
      Press
    </button>

I try to change the color of each button belonging to .list-button class after clicking on it using the following css code:

.list-button:focus {
  background-color: #7d698d;
}

However, while the color of the button I click each time changes (the color of all the previously clicked buttons also changes back to their original color). How could I fix it? I want all the clicked buttons to remain their new color.

I also tried assign an id to the buttons of this class and change their color inside the onClick() method as follows without success. The same problem remains. Could you help me, please?

  onclick(event: any) {
    const btn = document.getElementById('testID');
    if (btn) btn.style.backgroundColor = '#7d698d';
  }

CodePudding user response:

No need for js. Use the focus selector in your stylesheet.

The :focus selector is allowed on elements that accept keyboard events or other user inputs.

~ W3

button.list-button:focus {
  background-color: #7d698d;
  color: white;
}
<button >Click</button>

CodePudding user response:

You need to get the id of the button that fired the event

onclick(event: any) {
  const btn = document.getElementById(event.target.id);
  if (btn) btn.style.backgroundColor = '#7d698d';
}
  • Related