When working with multiple buttons in JavaScript, it can be essential to identify which button was clicked by the user to perform a specific action accordingly. In this blog post, we will learn how to find out which button is clicked using JavaScript event handling.
Using Event Listeners
To know which button was clicked, we can make use of event listeners. An event listener is a function that listens for a specified event. In our case, it will be listening for the click event. Here’s a step-by-step process on how to achieve this:
- Create your HTML buttons and assign each of them a unique ID.
- Write a JavaScript function that will handle the click event.
- Add event listeners to each button using their unique IDs, and pass the handleClick function as the callback.
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>
<button id="btn3">Button 3</button>
function handleClick(event) {
alert("Clicked button: " + event.target.id);
}
document.getElementById("btn1").addEventListener("click", handleClick);
document.getElementById("btn2").addEventListener("click", handleClick);
document.getElementById("btn3").addEventListener("click", handleClick);
Now, whenever any of the buttons are clicked, the handleClick function will be executed, and an alert will display the ID of the clicked button.
Using Inline Event Handlers
Another approach is to use inline event handlers, which means adding the onclick attribute directly to the HTML button element. Here’s how to do it:
- Create your HTML buttons and add the onclick attribute to each of them. Pass the handleClick function along with the this keyword as an argument.
- Write a JavaScript function that will handle the click event. This time, the function will receive the clicked button as an argument.
<button onclick="handleClick(this);">Button 1</button>
<button onclick="handleClick(this);">Button 2</button>
<button onclick="handleClick(this);">Button 3</button>
function handleClick(clickedButton) {
alert("Clicked button: " + clickedButton.textContent);
}
With this approach, whenever any of the buttons are clicked, the handleClick function will be executed, and an alert will display the text content of the clicked button.
Conclusion
In this blog post, we have explored two methods to identify which button was clicked in JavaScript. Both methods have their pros and cons, and the choice will depend on your specific requirements and coding preferences. Experiment with both methods to see which one works best for your projects.