I have a div of buttons in line and I want the user to be able to see when they selected a button by changing the CSS and it only going back to its old state when they select another button. Is this possible?
Advertisement
Answer
Find all the buttons and add event listener to execute some javascript where you put the logic of changing the behaviour of the buttons.
JavaScript
x
19
19
1
// Find all the buttons through their class names
2
buttons = document.querySelectorAll(".btn")
3
4
// loop through all the buttons
5
for (let i = 0; i < buttons.length; i++) {
6
let button = buttons[i];
7
8
// Add click event to buttons
9
button.addEventListener("click", function() {
10
11
// First remove 'clicked' class from all buttons
12
buttons.forEach(function(item){
13
item.classList.remove("clicked");
14
})
15
16
// Next add 'clicked' class to clicked button
17
button.classList.add("clicked");
18
});
19
}
JavaScript
1
5
1
/* class added through javascript to the buttons to change appearance of clicked
2
buttons */
3
.clicked {
4
background-color: coral;
5
}
JavaScript
1
5
1
<div>
2
<button type="button" class="btn">A</button>
3
<button type="button" class="btn">B</button>
4
<button type="button" class="btn">C</button>
5
</div>