0
let hidden_button = 'hidden-button'

test_button.addEventListener('click', (hidden_button) => {
    alert(hidden_button);
    myFunc(hidden_button)
})

I want to pass an variable hidden_button to the handler. But when I do as above and print out the alert, it says hidden_button is a MouseEvent. How do I pass arguments into the handler? Does whatever in the brackets () => refer to the event, which is a click? I found a few threads talking about addEventHandler but not the same problem I am looking at. Thanks.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Tristan Tran
  • 1,351
  • 1
  • 10
  • 36
  • 3
    why don't you use hidden_button directly in the click event () => { ... use hidden_button ... } – wangdev87 Nov 04 '20 at 03:31
  • @WilliamWang In my app, there is main button (i.e. ```test_button```) that is to trigger appropriate hidden elements to appear and apply ```myFunc``` on it. Here, that element is ```hidden_button```. So I can't do an ```addEventListener``` on the hidden button. – Tristan Tran Nov 04 '20 at 03:33
  • can you attach the minimum reproducible example - https://stackoverflow.com/help/minimal-reproducible-example? – wangdev87 Nov 04 '20 at 03:34
  • 3
    just use the variable `hidden_button` inside the handler code ... you've declared it ... so it's available ... the first (and only) argument to an event handler is the `event` - so, you can't change that (without using bind) ... i.e. `test_button.addEventListener('click', (x) => { alert(x); myFunc(x) }.bind(null, hidden_button))` - now `x` will be `hidden_button` – Jaromanda X Nov 04 '20 at 03:34
  • @Jaromanda X Thanks, This works now: ```let hidden_button = 'hidden-button' test_button.addEventListener('click', () => { alert(hidden_button); myFunc(hidden_button) })``` – Tristan Tran Nov 04 '20 at 03:37
  • 2
    that's exactly what @WilliamWang told you to do, so don't thank me – Jaromanda X Nov 04 '20 at 03:37
  • I see. I thought William was saying ```hidden_button.addEventListener```. Thanks both ! – Tristan Tran Nov 04 '20 at 03:38

0 Answers0