0
function my_function_name() { console.log('get it'); }
var eventname = 'click';
var functionname = 'my_function_name';
document.getElementById('test').addEventListener(eventname, functionname);

If I run those script, I get the following error: "Uncaught TypeError: EventTarget.addEventListener: Argument 2 is not an object."

What I have to do, that I can pass the second parameter of addEventListener as a variable?

  • Remove the quotes from the `functionname` definition: `var functionname = my_function_name`, but it seems kind of pointless? – BenM Mar 24 '22 at 16:41
  • 3
    Why would you even want to do that (pass the name of a function as string)? – Andreas Mar 24 '22 at 16:42
  • You need to pass the actual function to `addEventListener`, not its name: `.addEventListener(eventname, my_function_name)` – JLRishe Mar 24 '22 at 16:42
  • If you're asking how to turn a function name as a string into the real function, this might help: https://stackoverflow.com/questions/912596/how-to-turn-a-string-into-a-javascript-function-call – 0stone0 Mar 24 '22 at 16:43
  • The snippet is only the short form. Actually, I would like to set the events via data-attribute directly in the script. Something like
    . This data-attribut is then evaluated in the Javascript and the click event is then set on this DIV. Therefore, I would like to pass the function name dynamically.
    –  Mar 24 '22 at 16:47
  • 1
    Keep a `name => function` map and access your function by name on that map. Related: ["Variable" variables in JavaScript](https://stackoverflow.com/q/5187530/218196) – Felix Kling Mar 24 '22 at 16:49
  • `handleEvent` might be useful: https://webreflection.medium.com/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38 – Andreas Mar 24 '22 at 18:26

2 Answers2

0

You can assign your function to a variable like this

window.my_function_name = function() { console.log('get it'); }

Note that I'm using window object because I don't know how you define your scopes, but I'd suggest that you should keep your function in some other variables

And lastly, to access your function by that function name

document.getElementById('test').addEventListener(eventname, window[functionname]); //don't forget the bracket
Nick Vu
  • 14,512
  • 4
  • 21
  • 31
0

The reason your code is not working is because you are sending a string as the second parameter of addEventListener whereas it is expecting to receieve a function reference.

You can write like this.

 
var eventname = 'click';
var functionname = function(){ console.log('get it'); }
document.getElementById('test').addEventListener(eventname, functionname);
#test{
width:150px;
height:150px;
background-color:dodgerblue;
}
<div id = "test">

<div>