Handling Events

When users interact with your web page — like clicking a button or typing into a form — JavaScript can listen for those actions and respond. This ability to react to user actions is called handling events, and it's a key part of making a website dynamic and interactive.

addEventListener() basics

The addEventListener() method allows you to set up functions that run when a specific event happens. You can listen for clicks, typing, submitting forms, and much more.

Basic example:

javascript
1
2
3
4
5
          const button = document.querySelector('button');

button.addEventListener('click', function() {
  alert('Button was clicked!');
});
        

The first argument is the event name (like 'click'), and the second is the function to run when the event happens. This keeps your HTML and JavaScript nicely separated.

Mouse and keyboard events

There are many different types of events you can listen for. Some common mouse events include:

  • 'click' — when the user clicks
  • 'dblclick' — when the user double-clicks
  • 'mouseover' — when the mouse moves over an element

Common keyboard events include:

  • 'keydown' — when a key is pressed down
  • 'keyup' — when a key is released

Example of a keyboard event:

javascript
1
2
3
          document.addEventListener('keydown', function(event) {
  console.log('You pressed: ' + event.key);
});
        

Event object

When an event happens, JavaScript automatically passes an event object to the event handler function. This object contains useful details like which key was pressed, which element was clicked, or where the mouse was.

Example:

javascript
1
2
3
          button.addEventListener('click', function(event) {
  console.log(event.target); // logs the element that was clicked
});
        

preventDefault()

Sometimes you want to stop the default behavior of an element. For example, clicking a form's submit button normally reloads the page. You can prevent this using preventDefault():

javascript
1
2
3
4
5
6
          const form = document.querySelector('form');

form.addEventListener('submit', function(event) {
  event.preventDefault();
  console.log('Form submitted without page reload!');
});
        

This way, you can fully control what happens when users interact with your page.

Removing event listeners

If you want to stop listening to an event later, you can remove it using removeEventListener().

But you must pass the exact same function reference that was originally used with addEventListener().

Example:

javascript
1
2
3
4
5
6
7
8
          function handleClick() {
  console.log('Clicked!');
}

button.addEventListener('click', handleClick);

// Later you can remove it
button.removeEventListener('click', handleClick);
        

This is useful when you need to optimize performance or clean up event listeners when elements are removed from the page.