I was looking for javascript documentation and found this
JavaScript
x
8
1
const log = document.getElementById('log');
2
3
document.addEventListener('keydown', logKey);
4
5
function logKey(e) {
6
log.textContent += ` ${e.code}`;
7
}
8
I don’t understand how logkey function is working in addeventlistener . when I press a key, the console prints its code but logkey is not having any parameters in addeventlistener. How did it print e.code ?
Advertisement
Answer
You pass the function as a parameter to the eventListener. The eventListener calls the logKey function with the event as a function parameter.
See in the following example how a parameter is passed on to the function:
JavaScript
1
11
11
1
function func1(function_as_parameter){
2
function_as_parameter('Shivam');
3
}
4
5
function helloWordFunction(name){
6
console.log(`Hello ${name}!`);
7
}
8
9
func1(helloWordFunction); // Hello Shivam!
10
11