ЁЯЦ▒я╕П

JavaScript Events and Event Handling

Jul 18, 2024

JavaScript Events

Introduction

  • Events are an important and interesting part of JavaScript.
  • Through events, we can create interactive elements on websites.
  • Understanding events is essential for creating interactive and responsive websites.

Types of Events

  • Mouse Events: click, double click, mouse over
  • Keyboard Events: key press, key down, key up
  • Form Events: form submit
  • Clipboard Events: copy, paste
  • Window Events: window resize, load
  • Animation Events: animation start, end
  • Others: battery low event, environment events

Event Handling in JavaScript

  • Every node in the DOM can produce some type of event.
  • Events are generally used to trigger some work.
  • Event handling means making something happen after the event occurs.

Examples of Events

  • Display message on button click <!-- index.html --> <button onclick="alert('Hello')">Click Me</button> // script.js document.getElementById('button').addEventListener('click', () => { console.log('Button Clicked'); });

Event Listeners

  • Event listeners are used to listen and handle events.
  • Syntax: element.addEventListener(event, callback)
  • Event listeners allow us to access properties and methods in the variable. const button = document.querySelector('#button'); button.addEventListener('click', (e) => { console.log(e.type); // 'click' console.log(e.target); // target element });

Removing Event Listeners

  • Just like we add event listeners, we can also remove them. button.removeEventListener('click', handlerFunction);

Practical Example: Toggle Button for Dark/Light Mode

  • To create a toggle button that changes the mode of the webpage on click. <!-- index.html --> <button id="modeBtn">Change Mode</button> // script.js const modeBtn = document.querySelector('#modeBtn'); let currentMode = 'light'; modeBtn.addEventListener('click', () => { if (currentMode === 'light') { document.body.classList.add('dark'); document.body.classList.remove('light'); currentMode = 'dark'; } else { document.body.classList.add('light'); document.body.classList.remove('dark'); currentMode = 'light'; } }); /* style.css */ .dark { background-color: black; color: white; } .light { background-color: white; color: black; }

Summary

  • Event handling in JavaScript is very important to make the website interactive and responsive.
  • Homework: Add interactivity to an element on the page using mouse over event.

Further Reading