JAVASCRIPT Tutorial

Understanding the Event Object

Concept:

  • An event object is generated whenever an event (e.g., click, hover) occurs in a web page.
  • It contains information about the event, such as the target element, event type, and other details.

Practical Steps:

  1. Obtain the Event Object:
    • In event handling functions, the event object is accessible as the first parameter.
  2. Target Element:
    • event.target identifies the HTML element that triggered the event.
  3. Event Type:
    • event.type indicates the type of event that occurred (e.g., "click", "mouseover").
  4. Prevent Default Action:
    • event.preventDefault() prevents the browser's default behavior for the event (e.g., opening a link).
  5. Stop Event Propagation:
    • event.stopPropagation() prevents the event from bubbling up to parent elements.
  6. Event Information:
    • Access additional event information, such as:
      • event.clientX/event.clientY: Mouse cursor position in the page.
      • event.keyCode: Key pressed, if relevant.
      • event.ctrlKey/event.shiftKey/event.altKey: Modifier keys pressed.

JavaScript Example:

// Event listener for a button click
document.querySelector('button').addEventListener('click', (event) => {
  console.log(event.type); // "click"
  console.log(event.target); // Button element
  event.preventDefault(); // Prevent the page from reloading
});

Tips for Accessibility:

  • Use event.target.tagName to identify the type of element that triggered the event.
  • Consider using event.target.closest() to identify a parent element, if necessary.
  • Avoid using e as the parameter name for the event object, as it's commonly used in English and may not be accessible to screen readers.