JS DOM - 03.01 - Events

Manipulating DOM dynamically or on demand

Events

An event is a signal that something has happened. All DOM nodes generate such signals. Using js we can make the webpage listen and react to these events.

List of the most useful DOM events:

[[4.1 Mouse Events|Mouse events:]]

  • click – when the mouse clicks on an element (touchscreen devices generate it on a tap).
  • contextmenu – when the mouse right-clicks on an element.
  • mouseover / mouseout – when the mouse cursor comes over / leaves an element.
  • mousedown / mouseup – when the mouse button is pressed / released over an element.
  • mousemove – when the mouse is moved.

Keyboard events:

  • keydown and keyup – when a keyboard key is pressed and released.

Form element events:

  • submit – when the visitor submits a <form>.
  • focus – when the visitor focuses on an element, e.g. on an <input>.

Document events:

  • DOMContentLoaded – when the HTML is loaded and processed, DOM is fully built.

CSS events:

  • transitionend – when a CSS-animation finishes.

DOM Events

These allow js to add eventListener or eventHandler to HTML elements.

Here in HTML, onclick is the event listener and myFunction() is the event handler

<button onclick="myFunction()">CLick Me</button>
<button onclick="alert('hello')">CLick Me</button>

In this JS, click is the event listener and myFunction is the event handler

button.addEventListener("click", myFunction);

Explanation on other Events like click, dbclick, keydown, keyup

Other Events


Callback

A callback is simply a function that is passed into another function as an argument. When we pass in alertFunction() or function(e){..} as an argument to addEventListener this is a callback.

btn.addEventListener("click", function(e) {
	console.log(e.target)
});

btn.addEventListener("click", function(e) {
	e.target.style.background = "blue";
});

The e parameter in that call back function contains an object that references the event itself. within that object you have access to many useful properties and methods(functions that live inside an object) such that which mouse button or key was pressed, or information about the even’s target- the DOM node that was clicked. [[3.2 Event handlers#Event object|Event Object]]

Additional resources