Explain Codes LogoExplain Codes Logo

Onclick to get the ID of the clicked button

javascript
event-delegation
event-handling
button-interactions
Alex KataevbyAlex Kataev·Sep 18, 2024
TLDR

To get the ID of a clicked button, use event.target.id in an onclick handler. Let's say we have a button: <button id="myBtnId">Click Me</button>.

document.addEventListener('click', function(event) { if (event.target.tagName === 'BUTTON') { console.log('Clicked Button ID:', event.target.id); // Ain't no clickerino like a button clickerino! } });

This code snippet listens for click events, ensures a BUTTON was clicked, then logs its ID using event.target for an immediate ID reveal.

Unpacking button IDs and click events

Identifying the clicked button's ID unlocks the potential for custom behaviours triggered by different buttons. Here's a pragmatic exploration of possible patterns:

Direct ID passage

Inline handlers allow you to pass the ID directly to the function:

<button id="myButton" onclick="reply_click(this.id)">Button</button>

Then, your function could be:

function reply_click(clicked_id) { console.log('Button clicked:', clicked_id); // We've got an ID, let the party begin! }

Leveraging this in function

Capturing the this context when calling the function:

<button id="myButton" onclick="reply_click(this)">Button</button>

And the function would be:

function reply_click(button) { console.log('Button clicked:', button.id); // Thanks to `this`, we've got the ID! }

The importance of unique IDs

Make sure to give each button a unique id attribute. A valid ID starts with a letter and can be followed by letters, digits, hyphens, or underscores. A Highlander principle applies - there can be only one!

Structured event binding

To better distinguish HTML and Javascript roles, use this approach instead of inline onclick:

document.getElementById('myButton').addEventListener('click', function() { console.log('Clicked Button ID:', this.id); // MyButton just announced its ID, proud! });

Event Delegation for dynamic pages

For dynamic pages that refresh buttons after loading, Event Delegation can save your day:

document.addEventListener('click', function(event) { if (event.target.tagName.toUpperCase() === 'BUTTON') { reply_click(event.target.id); // Gather round buttons, it's ID reveal time! } }); function reply_click(clicked_id) { // Write custom functionality based on clicked_id }

Deep-diving into nuances

Event object's consistent properties

Use either event.target or event.srcElement to account for legacy browsers:

var clicked_id = event.target.id || event.srcElement.id; // Whichever comes first, we got the ID!

Debugging the click function

Debug your function by checking if console.log or alert is receiving the button's ID:

function reply_click(clicked_id) { console.log('Button ID:', clicked_id); // Quick check with an alert? De-comment the line below // alert('Button ID: ' + clicked_id); }

Inline vs. pure JavaScript

For maintainability and scalability, consider replacing inline event handlers with a pure JavaScript approach:

Array.from(document.querySelectorAll('button')).forEach(button => { button.addEventListener('click', function() { reply_click(this.id); // Paging all buttons for ID check! }); });

Wider applications

Click functions with multiple inputs

Sending additional data along with the ID can be done like this:

<button id="myButton" onclick="reply_click(this.id, 'Extra')">Button</button>
function reply_click(clicked_id, extra_input) { // Use both button ID and extra_input }

Optimizing additional event object properties

Extract more info by accessing other properties of the event object like event.type or event.stopPropagation().

Advanced button interactions

With the button ID, you can manage state changes, animate elements, navigate to other views, and make the UI dance!