Science Knowings: JavaScript Course For Social Media

Event Object

Event Object

Welcome back! In today's session, we'll dive into the Event Object, a fundamental aspect of event handling in JavaScript.

What is an Event Object?

An Event Object is a special object that contains information about an event that has occurred on an HTML element.

Properties of the Event Object

  • event.target: The HTML element that triggered the event.
  • event.type: The type of event that occurred (e.g., 'click', 'mousemove').
  • event.currentTarget: The element that actually handles the event.
  • event.timeStamp: The timestamp of when the event occurred.
  • event.pageX and event.pageY: The coordinates of the mouse cursor relative to the document.
  • event.clientX and event.clientY: The coordinates of the mouse cursor relative to the element.
  • event.key: The key that was pressed, if the event is a keyboard event.
  • event.modifiers: Any modifier keys (e.g., Shift, Ctrl) that were pressed during the event.

Event Object Methods

The Event Object also provides several methods:

  • event.preventDefault(): Prevents the default behavior of the event.
  • event.stopPropagation(): Stops the event from bubbling up the DOM.
  • event.stopImmediatePropagation(): Stops the event from bubbling up and also prevents any other event listeners on the same element from being triggered.

Synthetic Events

Synthetic events are events that are not triggered directly by user actions but are created by the browser or JavaScript code.

Handling Events with Event Listeners

We can handle events using Event Listeners. These are functions that are invoked when an event occurs on an element.

Adding Event Listeners

element.addEventListener('event_type', callback_function);

Here, event_type is the type of event to listen for (e.g., 'click'), and callback_function is the function that will be executed when the event occurs.

Removing Event Listeners

element.removeEventListener('event_type', callback_function);

To remove an event listener, use the removeEventListener() method.

Event Bubbling and Event Capturing

Event bubbling occurs when an event propagates up the DOM tree, triggering event handlers on all elements in its path. Event capturing, on the other hand, does the opposite, starting from the root element and moving down.

Event Delegation

Event delegation is a technique where you attach an event listener to a parent element instead of each individual child element. This can improve performance by reducing the number of event listeners.

Next Topic: Event Propagation (Bubbling vs Capturing)

In the next session, we'll dive deeper into Event Propagation, understanding how events bubble up and are captured in the DOM. Follow us to stay updated!