I have four buttons, I would like that each time one of them is clicked it has a blue border. And if another one is clicked, the previous one will immediately get back its usual border style.
I tried with loop but it doesn’t work
>Solution :
Here is an example of how you could implement this using JavaScript:
const buttons = document.querySelectorAll('button');
// Set the initial border style for all buttons
buttons.forEach(button => {
button.style.border = '1px solid black';
});
// Add a click event listener to each button
buttons.forEach(button => {
button.addEventListener('click', () => {
// Set the border style of all buttons to the initial style
buttons.forEach(b => {
b.style.border = '1px solid black';
});
// Set the border style of the clicked button to blue
button.style.border = '1px solid blue';
});
});
In this code, we first select all the button elements on the page using the querySelectorAll method. We then loop through each of the buttons and set their initial border style to 1px solid black.
Next, we add a click event listener to each button, which is triggered whenever the button is clicked. Inside the event listener, we again loop through all the buttons and set their border style back to the initial style. This ensures that all buttons have their initial style when any button is clicked.
Finally, we set the border style of the clicked button to 1px solid blue, which gives it the blue border that you want.
This code should give you the behavior you described, where each time a button is clicked it has a blue border and the previous button gets back its usual border style.