JavaScript Event Listeners

Jun 4, 2024

JavaScript Event Listeners

Introduction

  • Event-driven programming: Often used in web pages and hybrid mobile applications.
  • Javascript: An event-driven programming language.

Understanding Events

  • Events: User interactions such as tapping, clicking, swiping, typing, etc.
  • Examples of events: image finishing downloading, AJAX request completion, form submission, button click.

Common Event Types

  • Click: User clicks on an element (e.g., button, link).
  • Load: Element or resource loaded (e.g., image, document).
  • Input: User inputs text into a form field.
  • Blur: Element loses focus.
  • Mouse Events: Mousedown, mouseup, mouseover, etc.

Syntax

  • Basic syntax involves attaching an event listener to a DOM element.
let element = document.getElementById('someElement');
element.addEventListener('event', functionName);
  • addEventListener method is used to set up an event listener.

Example

let myDiv = document.getElementById('myDiv');
myDiv.addEventListener('click', doSomething);

function doSomething(event) {
  // Event handling code
}
  • Event parameter: Passed to event handler functions, containing information about the event.
  • Properties:
    • event.type: Type of event (e.g., click).
    • event.target: Element that triggered the event.
    • event.currentTarget: Element to which the event handler is attached.

Anonymous Functions and Arrow Functions

  • Instead of named functions, anonymous or arrow functions can be used.
element.addEventListener('click', function(event) {
  // handle code
});
  • Arrow Functions:
element.addEventListener('click', (event) => {
  // handle code
});

Preventing Default Behavior

  • Links and form submissions have default behaviors.
  • Use event.preventDefault() to prevent the default action.
link.addEventListener('click', function(event) {
  event.preventDefault();
  // handle click
});

Practical Examples

  • Elements: Button, link, input field.
  • Actions:
    • Button click logs event type and target.
    • Link click prevented from navigating, logs event type and target.
    • Input field logs entered text on input/leaving field.

Ensuring Elements Exist Before Adding Listeners

  • Placing Script Tags: Script tags should be placed at the end of the body to ensure elements are loaded before script execution.
  • Alternative: Using DOMContentLoaded event.
document.addEventListener('DOMContentLoaded', function() {
  // add event listeners here
});

Example HTML and Script

<!DOCTYPE html>
<html>
<head>
  <script src="path/to/script.js"></script>
</head>
<body>
  <button id="btn">Click me</button>
  <a id="lnk" href="https://google.com">Google</a>
  <input type="text" id="txt" />
</body>
</html>

Corresponding Script

document.addEventListener('DOMContentLoaded', () => {
  let btn = document.getElementById('btn');
  let lnk = document.getElementById('lnk');
  let txt = document.getElementById('txt');
  
  btn.addEventListener('click', (event) => {
    console.log(event.type);
    console.log(event.target);
  });

  lnk.addEventListener('click', (event) => {
    event.preventDefault();
    console.log(event.type);
    console.log(event.target);
  });

  txt.addEventListener('input', (event) => {
    console.log(event.target.value);
  });
});

Conclusion

  • JavaScript event listeners are crucial for interactive web pages.
  • Key points: Understanding events, using addEventListener, preventing default behaviors, and ensuring element existence before adding listeners.

Questions: Leave any questions in the comments.