How To Know Which Button Is Clicked In Javascript

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:

  1. Create your HTML buttons and assign each of them a unique ID.
  2. <button id="btn1">Button 1</button>
    <button id="btn2">Button 2</button>
    <button id="btn3">Button 3</button>
  3. Write a JavaScript function that will handle the click event.
  4. function handleClick(event) {
        alert("Clicked button: " + event.target.id);
    }
  5. Add event listeners to each button using their unique IDs, and pass the handleClick function as the callback.
  6. 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:

  1. 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.
  2. <button onclick="handleClick(this);">Button 1</button>
    <button onclick="handleClick(this);">Button 2</button>
    <button onclick="handleClick(this);">Button 3</button>
  3. Write a JavaScript function that will handle the click event. This time, the function will receive the clicked button as an argument.
  4. 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.