Edit Page

Mouse and Keyboard Events in JavaScript

Mouse Events

Mouse events are triggered when using a pointer device like the mouse. The most common events are: click, dbclick, mouseup and mousedown. There are two approaches for registering mouse or any event handlers in general:

  1. inline in the HTML using the onevent property (e.g. onclick for the click event).
  2. Dynamically in JS by adding the event handler to the element in the DOM tree using the addEventListener() method.

1) Registering Mouse Events Inline (in HTML)

We can add mouse events inline in HTML using the onevent property. For example, the click event can be registered using the onclick property and assigning it to the a function with parentheses for invocation as shown in the following example:

60%

2) Registering Mouse Events in the DOM (in JS)

We can register mouse events in JavaScript using addEventListener of the DOM element and assigning it to the function name ** without parentheses** so it will be invoked when the event is fired inside the addEventListener function as in the following example:

60%

Keyboard events

Keyboard events are triggered when interacting with the keyboard. There are two keyboard events: keydown (a key has been pressed) and keyup (a key has been released). Similar to mouse events, there are two approaches for registering keyboard or any event handlers in general:

  1. Inline in the HTML using the onevent property (e.g. onkeydown for pressing a key and onkeyup for releasing a key).
  2. Dynamically in JS by adding the event handler to the element in the DOM tree using the addEventListener() method.

1) Registering Keyboard Events Inline (in HTML)

We can add keyboard events inline in HTML using the onevent property. For example, the key up event can be registered using the onkeyup property and assigning it to the a function with parentheses for invocation. The following example uses the onkeyup event to listen to key press and release events to convert numbers entered in Arabic numerals to English numerals.

60%

2) Registering Keyboard Events in the DOM (in JS)

Similar to registering mouse events, we can register keyboard events in JavaScript using addEventListener of the DOM element and assigning it to the function name without parentheses so it will be invoked when the event is fired inside the addEventListener function as in the following example:

60%

Removing Registered Mouse or Keyboard Events

We can remove registered mouse or keyboard events using removeEventListener as shown in the following example:

60%

Complete Example

The following example shows how to filter a table by a word and/or by an item in a drop down menu.

60%