DEV Community

Rakshambika
Rakshambika

Posted on

Events in JS

When we build a web page, we don't want it to just display information. We want it to respond to the user's actions.

For example:

  • Clicking a button
  • Typing in an input box
  • Moving the mouse
  • Submitting a form
  • Loading a page
  • Pressing a keyboard key

These actions are called events in JavaScript.


What is Events?

  • An event is an action or occurrence that happens in the browser and can be detected by JavaScript.

For example, when a user clicks a button:

<button>Click Me</button>
Enter fullscreen mode Exit fullscreen mode

The click is an event.

JavaScript can listen for this event and execute some code when it happens.

button.addEventListener("click", function() {
    console.log("Button clicked!");
});
Enter fullscreen mode Exit fullscreen mode

Here:

click → Event
addEventListener() → Listens for the event
function() → Code executed when the event occurs


Why Do We Need Events?

  • Events make web pages interactive. Without events, a button would simply be a button.

With events, we can make it:

  • Show a message
  • Change text
  • Change styles
  • Open/close menus
  • Submit forms
  • Validate user input
  • Fetch data from an API
  • Add or remove elements

For example:

button.addEventListener("click", function() {
    document.body.style.backgroundColor = "lightblue";
});

Enter fullscreen mode Exit fullscreen mode

Now the background changes when the user clicks the button.


JavaScript Events

There are many events available in JavaScript.

Some commonly used ones are:

Event When it occurs
click When the user clicks an element
dblclick When the user double-clicks an element
mouseover When the mouse pointer moves over an element
mouseout When the mouse pointer leaves an element
mousedown When a mouse button is pressed
mouseup When a mouse button is released
mousemove When the mouse pointer moves
keydown When a keyboard key is pressed
keyup When a keyboard key is released
input When the value of an input changes
change When the value of an input or select element changes
submit When a form is submitted
focus When an element receives focus
blur When an element loses focus
load When a page or resource finishes loading

Top comments (0)