Onclick to get the ID of the clicked button
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>
.
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:
Then, your function could be:
Leveraging this
in function
Capturing the this
context when calling the function:
And the function would be:
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
:
Event Delegation for dynamic pages
For dynamic pages that refresh buttons after loading, Event Delegation can save your day:
Deep-diving into nuances
Event object's consistent properties
Use either event.target
or event.srcElement
to account for legacy browsers:
Debugging the click function
Debug your function by checking if console.log
or alert
is receiving the button's ID:
Inline vs. pure JavaScript
For maintainability and scalability, consider replacing inline event handlers with a pure JavaScript approach:
Wider applications
Click functions with multiple inputs
Sending additional data along with the ID can be done like this:
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!
Was this article helpful?