Event Handling

Event Handling refers to the process of registering an event listener on a specific element in the HTML document and then writing JavaScript code to handle the event when it is triggered. Events can be user-generated, such as a mouse click or a key press, or they can be triggered by the browser, such as the page finishing loading.

Here are some common event listeners in JavaScript along with examples of how to use them:

  1. click: This event listener is triggered when the user clicks on an element.

const button = document.querySelector('#myButton');
button.addEventListener('click', () => {
  alert('Button clicked!');
});
  1. mouseover: This event listener is triggered when the mouse moves over an element.

const element = document.querySelector('#myElement');
element.addEventListener('mouseover', () => {
  element.style.backgroundColor = 'red';
});
  1. keydown: This event listener is triggered when a key is pressed down.

document.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    console.log('Enter key pressed');
  }
});
  1. submit: This event listener is triggered when a form is submitted.

const form = document.querySelector('#myForm');
form.addEventListener('submit', (event) => {
  event.preventDefault(); // prevents the form from submitting
  console.log('Form submitted');
});
  1. load: This event listener is triggered when the page has finished loading.

window.addEventListener('load', () => {
  console.log('Page loaded');
});
  1. resize: This event listener is triggered when the browser window is resized.

ewindow.addEventListener('resize', () => {
  console.log('Window resized');
});
  1. scroll: This event listener is triggered when the user scrolls the page.

window.addEventListener('scroll', () => {
  console.log('Page scrolled');
});

These are just a few examples of the many event listeners available in JavaScript. By registering event listeners and writing code to handle the events, you can create dynamic and interactive web pages.

Last updated