JAVASCRIPT Tutorial

Event Types in JS

Event types are actions that trigger JavaScript functions. Understanding event types is crucial for creating interactive web applications.

Key Concepts:

  • Event: An action that occurs on an element, such as clicking a button or moving the mouse.
  • Event Type: A specific type of event, such as "click" or "mouseover."
  • Event Listener: A function that is executed when an event occurs.

Common Event Types:

  • click: Occurs when a user clicks on an element.
  • mouseover: Occurs when the mouse cursor enters an element.
  • mouseout: Occurs when the mouse cursor leaves an element.
  • keydown: Occurs when a key on the keyboard is pressed.
  • keyup: Occurs when a key on the keyboard is released.
  • submit: Occurs when a form is submitted.
  • load: Occurs when a page or image is fully loaded.
  • resize: Occurs when the browser window is resized.

Adding Event Listeners:

To add an event listener, use the addEventListener() method. The syntax is:

element.addEventListener(event_type, event_listener_function, useCapture);
  • element: The element to listen for events on.
  • event_type: The type of event to listen for.
  • event_listener_function: The function to execute when the event occurs.
  • useCapture: Optional boolean indicating whether to use the "capture" phase of event propagation.

Example:

const button = document.getElementById("myButton");

// Add a click event listener to the button
button.addEventListener("click", function() {
  console.log("Button clicked!");
});

Conclusion:

Event types are essential for creating interactive web applications. By understanding common event types and how to add event listeners, you can respond to user actions and create dynamic and responsive web pages.