0

I am trying to pass arguments to a function inside my eventlistener for my school assignment in the code below. I am a newbie in JS and found out here Javascript event handler with parameters, that you can't just pass parameters to an eventlistener's function. But otherwise this thread wasn't much help. Simply because I don't really know JS and didn't understand it. How can I do it?

document.getElementById("Content_id").addEventListener("focus", focusFunction ("Content_id",event);});


function focusFunction(elID,event){
    alert(elID+":"+event.timestamp);
}
artre
  • 311
  • 4
  • 14
  • 2
    You are *immediately invoking* that function, you are not attaching it as an event listener. – VLAZ Sep 05 '19 at 10:44

2 Answers2

2

document.getElementById("Content_id").addEventListener("focus", function(event) {
  focusFunction(event);
});

function focusFunction(event) {
  console.log(event.target.id + ":" + event.timeStamp); //event.target.id is more dynamic
}
<input id="Content_id" />
alexP
  • 3,672
  • 7
  • 27
  • 36
  • Worked like a charm, thanks! Question: what do you mean with your comment? something like : the event.target.id can change during the event?? – artre Sep 05 '19 at 11:02
  • Take a look [here](https://jsfiddle.net/7mbr30nw/). In that case your selector is class instead of a fix id but you can still use `focusFunction`. – alexP Sep 05 '19 at 11:26
0

You need to wrap the callback into a function, otherwise it will be invoked straight away:

document.getElementById("Content_id").addEventListener("focus", (event) => focusFunction("Content_id", event));
Clarity
  • 10,730
  • 2
  • 25
  • 35