Javascript Events

Events are actions or occurrences that happen in the system you are programming, which the system tells you about so you can respond to them in some way if desired. For example, if the user clicks a button on a webpage, you might want to respond to that action by displaying an information box.

When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other examples include events like pressing any key, closing a window, resizing a window, etc.

There are different types of Events in Javascript which you can register and react to it.

Here are the basic Events which is widely used on most of the websites.

EventDescription
onchangeAn HTML element has been changed
onclickThe user clicks an HTML element
onmouseoverThe user moves the mouse over an HTML element
onmouseoutThe user moves the mouse away from an HTML element
onkeydownThe user pushes a keyboard key
onloadThe browser has finished loading the page

Example:

A simple example

Let’s look at a simple example to explain what we mean here. You’ve already seen events and event handlers used in many of the examples in this course already, but let’s recap just to cement our knowledge. In the following example, we have a single <button>, which when pressed, makes the background change to a random color:

<button>Change color</button>

The JavaScript looks like so:

const btn = document.querySelector('button');

function random(number) {
  return Math.floor(Math.random() * (number+1));
}

btn.onclick = function() {
  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
  document.body.style.backgroundColor = rndCol;
}