Q: Alternative to anonymous functions in JavaScript 

document.addEventListener('DOMContentLoaded', function() {
  let input = document.querySelector('input');
  input.addEventListener('keyup', function(event) {
    let name = document.querySelector('#name');
    if (input.value) {
      name.innerHTML = `hello, ${input.value}`;
    } else {
      name.innerHTML = 'hello, whoever you are';
    }
  });
});
<form>
  <input autocomplete="off" autofocus placeholder="Name" type="text">
</form>
<p id="name"></p>


In the above HTML page, they have used anonymous functions to look for keyup event and greet with the word we have typed/input.
How do I achieve this without using anonymous functions? So far I have tried modifying the script, but it fails to identify keyup event


function greet() {
  let name = document.querySelector("#name");
  let event = document.querySelector("input");
  if (event.value) {
    name.innerHTML = `HELLO ${event.value}`
  } else {
    name.innerHTML = `HELLO person`
  }
}

function listen() {
  let input = document.querySelector("input");
  input.addEventListener("keyup", greet);
}

document.addEventListener("DOMContentLoaded", listen);



A: You have to pass event object to your event handler functions instead of trying to read arbitrary DOM elements, like so:


function greet(event)
{
   let name = document.querySelector("#name");

   if (event.target.value) {
         name.innerHTML = `HELLO ${event.target.value}`
   } else {
         name.innerHTML = `HELLO person`
   }
}

function listen()
{
   let input = document.querySelector("input");
   input.addEventListener("keyup", greet);
}

document.addEventListener("DOMContentLoaded", listen);
<div id="name">HELLO person</div>
<div>
  <input type="text" name="name" />
</div>


