Home > front end >  why does function() need to be typed before the function name when using onkeydown in javascript?
why does function() need to be typed before the function name when using onkeydown in javascript?

Time:03-09

I'm pretty new to javascript, and I was practicing a bit with events on W3Schools. In their tutorial, they show this line of code:

document.getElementById("demo").onkeydown = function() {myFunction()};

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}

I don't understand why you have to type function() {function name()} rather than just typing the function you are trying to call. Basically, I'm not understanding the logic behind that line of code. Can someone please explain it to me?

CodePudding user response:

You don't need function, you can just put the function name there.

document.getElementById("demo").onkeydown = myFunction;

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}
<input id="demo">

You would need to wrap it inside another function if you wanted to do more than just call the function directly.

document.getElementById("demo").onkeydown = function() {
  console.log("Keydown");
  myFunction();
};

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}
<input id="demo">

CodePudding user response:

You can do it, you must pass it as reference:

document.getElementById("demo").onkeydown = myFunction(); - myFunction will be called immediately and not as callback. Callback would be return value of myFunction.

You them assign it as reference:

document.getElementById("demo").onkeydown = myFunction - note that you can't pass parameters at runtime here!

CodePudding user response:

In the example you give:

document.getElementById("demo").onkeydown = function() {myFunction()};

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}

the value of the onkeydown property of an element must be a function - not a call to a function. So you could not have for example:

  document.getElementById("demo").onkeydown = myFunction();

What that would do would be to try to run myFunction and put the result from that into the onkeydown property.

Actually it would fail as at the time the system tried to run it that function doesn't yet exist.

What you could do is declare the function first and then use that as the value for the assignment.

function myFunction() {
  document.getElementById("demo").style.backgroundColor = "red";
}
document.getElementById("demo").onkeydown = myFunction;
  • Related