0

I have a setup where I have two buttons on a page. On button 1 i'm triggering a click on button 2. On button 2 I have a function that runs when its clicked. But I need to tell in that function if it was button 1 or button 2 that was clicked.

Here is some basic code:

document.getElementById('btn2').onclick = function(event) {
 // if button 1... else if button 2...
 alert('I cant tell which button was clicked. '+ event.target.id  +' was clicked.');
};
<div>
  <button id="btn1" onclick="document.getElementById('btn2').click()">Button 1</button>
  <button id="btn2">Button 2</button>
</div>

You will see that in the click function event.target.id will show the id of button 2 when button 1 is clicked.

Davyd
  • 181
  • 12

1 Answers1

0

Instead of triggering a click on button 2 from button 1, place the shared logic in a separate function that is called from two different click events in button 1 and button 2. Then you'll be able to add whatever logic you want before/after the shared logic for each different button

Miss Skooter
  • 803
  • 10
  • 22
  • In my use case I don't control the events already button 2 so I wanted to trigger with button 1 then be able to tell in a click function which was actually clicked. – Davyd Feb 07 '23 at 22:25