How can i change an already clicked button, color, back to original when another button is clicked

Viewed 32

So what i basically want is when a button is clicked, it'll change the background-color to orange, and when i click on another button, i want the button that was clicked previously to change color to its original.

const subBtn = document.getElementById('submit');
const card = document.getElementById('card');



button.forEach(btn => {
    btn.addEventListener('click', e => {
        btn.style.backgroundColor = "#7C8798";
        btn.style.color = 'white';

    })
})


subBtn.addEventListener('click', e => {
    subBtn.style.backgroundColor = 'white';
    subBtn.style.color = '#FC7614'
});
2 Answers

Did you tried active in css?

.btn:active {
   background-color: orange;
   color: white
}

Then add the css class via JavaScript

btn.classList.add('btn');

As I understand, you have two buttons and willing to change the style properties of one card. In your code button is not defined and the HTML element id should be unique for each tag. So rather than iterating undefined elements, can create two buttons in HTML and add unique ids to them.

<div id="card">
    <button id="orange">Original->Orange</button>
    <button id="original">Orange->Original</button>
</div>

And getting elements by their ids.

const subBtn = document.getElementById('orange');
const subBtn2 = document.getElementById('original');
const card = document.getElementById('card');

subBtn.addEventListener('click', () => {
  card.style.backgroundColor = '#7C8798';
  card.style.color = 'white';
});

subBtn2.addEventListener('click', () => {
  card.style.backgroundColor = 'white';
  card.style.color = '#FC7614';
});
Related