I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one event listener for all the buttons, but how do I identify which button was clicked based on its ID?
<div class="col-11" id="btns">
<button class="btn btn-dark" id="btn1">Button 1</button>
<button class="btn btn-dark" id="btn2">Button 2</button>
<button class="btn btn-red" id="btn3">Button 3</button>
<button class="btn btn-blue" id="btn4">Button 4</button>
</div>
let btnContainer = document.getElementById('btns');
btnContainer.addEventListener("click", handleButtonClick);
function handleButtonClick(e){
if(e.target.id === 'btn1'){
console.log("Hello");
} else if(e.target.id === 'btn2'){
// do something...
}
}