While Christopher Taleck's answer is perfectly fine, I have an alternative way to approach this problem that may be informative for others facing a similar situation.
For a working example, you can check out this JSFiddle: JSFiddle
Below is the complete code along with explanations:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Button Practice</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="network-container">
<h2>Network</h2>
<button type="button" class="btn25">MTN</button>
<button type="button" class="btn25">Glo</button>
<button type="button" class="btn25">9 Mobile</button>
<button type="button" class="btn25">Airtel</button>
</div>
<div class="speed-container">
<h2>Speed</h2>
<button type="button" class="btn25">1Mbps</button>
<button type="button" class="btn25">2Mbps</button>
<button type="button" class="btn25">3Mbps</button>
<button type="button" class="btn25">5Mbps</button>
<button type="button" class="btn25">10Mbps</button>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
script.js
function ButtonContainer(element) {
this.element = element;
this.selectedButton = null;
this.element.addEventListener('click', function(e) {
if (e.target.type !== 'button') return;
if (this.selectedButton) this.selectedButton.classList.remove('active');
e.target.classList.add('active');
this.selectedButton = e.target;
});
}
const networkContainer = new ButtonContainer(document.querySelector('.network-container'));
const speedContainer = new ButtonContainer(document.querySelector('.speed-container'))
style.css
.active {
background-color: #9AD58E;
}
GENERAL CODE EXPLANATION
To improve readability and maintainability, it's recommended to separate the JavaScript from the HTML. Create a constructor function called ButtonContainer that handles button interactions within specific container elements:
// script.js
function ButtonContainer(element) {
// Constructor function implementation
}
ButtonContainer CONSTRUCTOR FUNCTION EXPLANATION
The ButtonContainer constructor function sets up properties for the respective element and selected button. It adds event listeners for button clicks within the container element and updates the styling accordingly.
By creating instances of ButtonContainer for different groups of buttons, you streamline event handling and keep code organized:
const networkContainer = new ButtonContainer(document.querySelector('.network-container'));
const speedContainer = new ButtonContainer(document.querySelector('.speed-container'));
This approach simplifies button management and reflects the logical separation between different button groups in the UI.