Mark As Completed Discussion

Event Object

When an event is triggered in JavaScript, additional information about the event is passed to the event handler function. This information is encapsulated within an object called the event object.

The event object provides valuable data and functionality related to the event that occurred. It contains properties such as:

  • event.type: Indicates the type of event that occurred, such as 'click', 'keydown', or 'mousemove'.
  • event.target: Refers to the element on which the event occurred.
  • event.clientX and event.clientY: Provide the horizontal and vertical coordinates of the mouse pointer at the time of the event.
  • event.key: Contains the value of the key that was pressed during a keyboard event.

Here's an example of a click event listener that logs information from the event object:

JAVASCRIPT
1const button = document.getElementById('my-button');
2
3button.addEventListener('click', event => {
4  console.log('Button clicked!');
5  console.log('Event:', event);
6});

When you click the button, it will log the message 'Button clicked!' and the event object to the console. You can explore the event object further to access its properties and utilize them for different purposes.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment