1

See my code, I'm defining a function to call the function outside. But I want to simplify it as ("click",myFunction(e)) but e(event) is not transfering to the function. My point of view: how to

The code working properly: how to send event object to the fucntion proparly without adecribing anonymous function on addEvenListener

document.querySelector("#b1").addEventListener("click",function (e){myFunction(e)})

function myFunction(e) {
    document.getElementsByTagName('h5')[0].innerHTML=e.target.tagName};

The code is not working:

document.querySelector("#b1").addEventListener("click",myFunction(e))

function myFunction(e) {
    document.getElementsByTagName('h5')[0].innerHTML=e.target.tagName};
uyanikm
  • 21
  • 3
  • 2
    In the second version you're calling the function immediately when you call `addEventListener()`, not when the event occurs. – Barmar Jun 19 '23 at 23:01
  • 2
    Try simply `addEventListener("click", myFunction)` – Barmar Jun 19 '23 at 23:02
  • Thanks for that `addEventListener("click", myFunction)` solved my problem. I can bet I tried that also but probably there was other problem. Beside that why `addEventListener("click", myFunction(e))` calling the function immediately ? I'm just passing an argument on it. Is it not possible to pass argument with addEventListener ? – uyanikm Jun 20 '23 at 08:02
  • When you call a function with arguments, the arguments are first evaluated, and their values are passed to the function. So `addEventListener("click", myFunction(e))` is equivalent to `temp = myFunction(e); addEventListener("click", temp);` If you want to call a function with arguments, you have to use an anonymous function as the callback, like your first snippet. – Barmar Jun 20 '23 at 14:58

0 Answers0