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:
- inline in the HTML using the onevent property (e.g.
onclick
for the click event). - 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:
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:
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:
- Inline in the HTML using the onevent property (e.g.
onkeydown
for pressing a key andonkeyup
for releasing a key). - 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.
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:
Removing Registered Mouse or Keyboard Events
We can remove registered mouse or keyboard events using removeEventListener
as shown in the following example:
Complete Example
The following example shows how to filter a table by a word and/or by an item in a drop down menu.