cover-img

Explain Event Objects

20 January, 2023

3

3

0

In JavaScript, when an event is triggered on an element, an event object is automatically passed as an argument to the event listener function. This event object contains information about the event, such as the type of event, the target element, and the time at which the event occurred.

The event object is a standard JavaScript object and is often referred to as the event or e object. It has various properties that provide information about the event, such as:

  • type: The type of event (e.g., "click", "submit", "load")
  • target: The element that triggered the event (e.g., the button that was clicked)
  • currentTarget: The element that the event listener is attached to (it's the same as this inside the function)
  • timeStamp: The number of milliseconds since the document was loaded, indicating when the event occurred
  • preventDefault(): A method to stop the default behaviour of the event
  • stopPropagation(): A method to stop the event from bubbling up to parent elements

Here is an example of how you could use the event object to get information about a click event:

var button = document.getElementById("myButton");
button.addEventListener("click", function(event) {
console.log(event.target); //log the button element
console.log(event.type); //log the event type 'click'
console.log(event.timeStamp);//log the time of the event
});

It's also possible to use the preventDefault() and stopPropagation() method to halt the event's default behaviour and stop it from bubbling up to parent elements.

button.addEventListener("click", function(event) {
event.preventDefault();
event.stopPropagation();
});

In this example, when the button is clicked, the event listener function is called and the event object is passed as an argument. The code inside the function uses properties of the event object to log information about the event to the console, such as the target element and the type of event.

It's also important to note that the event object is only valid for the duration of the event listener callback and is no longer available after that. It also has different properties and methods that depend on the type of event.

3

3

0

ShowwcaseHQ
Showwcase is where developers hang out and find new opportunities together as a community

More Articles