JavaScript event listeners & arguments

Hello,

I am looking for a way to write an event listener that does something with a clicked element, but can also take an argument.

For example:

function myEventListener() {
myVar = event.target.id
// do something with myVar
}

Or

function myEventListener(myArg) {
// do something with myArg
}

So basically I’m looking for the best way to not have to repeat code. Like, if I want to highlight an element with a certain color when the element is clicked, but also be able to highlight the element by entering it as an argument myself.

Is this more of an event handler?

1 Like

Oh perhaps I am using the wrong term? I always get the two confused.

1 Like

The ‘listener’ is a JS object we attach to our DOM node, along with a callback, a handler reference.

node = document.querySelector('#node');
callback = function (e) {
    // handler action(s)
}
node.addEventListener('click', callback)

Note that the parameter, e represents the transient event object, and as such comes in with a load of attributes that all directly relate to both the event and the target or I/O, &c.

1 Like

If you’re really brave, and only when you are comfortable with events, may I challenge you to create a document containing a single object on the page with which to interact, and then have a program append to the document each event it detects. Filter out methods, and only print the data attributes. This project on your Github or CV will be impressive, to say the least. AND, it will serve you well as you develop interactive web apps.

Proviso

Yes, I know what is involved in this process but wrote my code more than a decade ago in jQuery, and the code now long lost. So I know it can be done, but there are some challenges along the way, mostly fighting one’s own bias or assumptions. It took me days to work up a solution. Ultimately you will have a take away, and I’ll get to see that list of data attributes again.

You have our assistance at your disposal. Surely more than just me would like to be involved or get a better look under the hood. It’s a take away for everyone.

1 Like

For instance:

<form action="">
  <input>
  <textarea>

  </textarea>
</form>

The events detected in the input field would be echoed in the textarea. That’s one scenario, among many others. We just want to see the event attributes for the most recent event.

I guess you could check if the argument is an Event object or Element object using instanceof for the event handler function.

function turnTextBlue(eventOrElement) {
  let element;
  if (eventOrElement instanceof Event) {
    element = event.target; // if argument is an event, then .target is the element
  }
  else {
    element = eventOrElement;
  }
  // turn the text blue by changing stuff in the style attribute/property
  element.style.color = "blue";
}

That has nothing to do with a list of event attributes apart from the target; but it does query the instance existence. That may be helpful.

Im confused as to what is the purpose of an event as a function parameter. Im doing the piano keys exercise
and Im confused as to why do we use event as a parameter. Ive looked online and the explanations still dont make sense. can anyone give me a simple explanation Please
. Thank you.

const keyReturn = function (e){

event.target.style.backgroundColor = “”;

}

const keysList = function(note){

note.onmousedown= function(){

keyPlay(event);

}

note.onmouseup= function(){

keyReturn(event);

}

};

We use an event as a parameter so that we can use information about the event, such as its target, as parameters within the function.

That first keyReturn function, for example, changes the background color of the event’s target to blank when it is called. Let’s say I want that to happen to a button I created: I would add an event listener to the button so that whenever the “click” event occurs on it, the background changes. Might look like this:

<button id="background-button">Change this background</button>

<script>
    const backgroundButton = document.getElementById('background-button')

    backgroundButton.addEventListener("click", keyReturn)
</script>

Now whenever that button is clicked, the event listener will trigger and call keyReturn with the event object that’s created by the click as its parameter. The keyReturn function, then, will automatically be “targetting” my background button.

event in that context is the global event object. However, that is what e is in the parameter so your code could read,

e.target.style...

I used chatgpt to generate some code, does this work?

Event Handling Example Click Me
<script>
  const button = document.getElementById('my-button');

  // Define a callback function to log data attributes
  function logDataAttributes(event) {
    // Prevent default behavior of the event
    event.preventDefault();

    // Filter out methods and log data attributes
    const dataAttributes = Object.entries(event)
      .filter(([key, value]) => typeof value !== 'function')
      .map(([key, value]) => `${key}: ${JSON.stringify(value)}`);

    console.log(dataAttributes);
  }

  // Attach event listeners to the button
  button.addEventListener('click', logDataAttributes);
  button.addEventListener('mouseover', logDataAttributes);
  button.addEventListener('mouseout', logDataAttributes);
</script>

Maybe you could try building a tiny, toy HTML page to go along with that and test out whether it works. But yeah, it looks like it should work.

Haven’t tried this in a sandbox, yet, but in the Chrome console:

 > body = document.querySelector('body')
<- <body>​</body>​
 > buttonEl = document.createElement('button')
<- <button>​</button>​
 > text = document.createTextNode('Click Me!')
<- "Click Me!"
 > buttonEl.appendChild(text)
<- "Click Me!"
 > body.appendChild(buttonEl)
<- <button>​Click Me!​</button>​
 > output = document.createElement('p')
<- <p>​</p>​
 > body.appendChild(output)
<- <p>​</p>​
 > button = document.querySelector('button')
<- <button>​Click Me!​</button>​
 > p = document.querySelector('p')
<- <p>​</p>​
 > function logDataAttributes(event) {
       event.preventDefault();
       const dataAttributes = Object.entries(event)
         .filter(([key, value]) => typeof value !== 'function')
         .map(([key, value]) => `${key}: ${JSON.stringify(value)
       }`);
       p.textContent = dataAttributes;
   }
<- undefined
 > button.addEventListener('click', logDataAttributes)
<- undefined
 > button.addEventListener('mouseover', logDataAttributes)
<- undefined
 > button.addEventListener('mouseout', logDataAttributes)
<- undefined

All I’m getting for output is,

isTrusted: true

and none of the expected event attributes.

It does say something for ChatGPT, but I’m a tad disappointed that a human didn’t think this through and go about the testing and debugging that would have been involved. One supposes this is what we should be looking forward to, going on.