Skip to content

Event listeners

Attaching an event listener

We can listen for events such as 'click' or 'mouseenter' and trigger listener functions in response.

js
const shareBtn = document.querySelector('#shareBtn')

function shareMovie() {
  window.alert('You shared me!')
}

shareBtn.addEventListener('click', shareMovie)
html
<button id="share-btn" class="btn-icon">
  <span class="icon material-icons">share</span>
</button>

Using arrow functions

We can use arrow functions to reduce the verbosity of our code.

js
shareBtn.addEventListener('mouseenter', () => {
  console.log('That tickles!')
})

Common events

Here are some of the different events you can listen for in the DOM:

Event NameDescription
clickFires when a pointing device button (usually a mouse button) is clicked on an element.
dblclickFires when a pointing device button is double-clicked on an element.
mousedownFires when a pointing device button is pressed down on an element.
mouseupFires when a pointing device button is released over an element.
mouseoverFires when a pointing device is moved onto an element.
mouseoutFires when a pointing device is moved off an element.
mousemoveFires when a pointing device is moved while over an element.
keydownFires when a key is pressed down on the keyboard.
keyupFires when a key is released on the keyboard.
keypressFires when a key is pressed down and then released on the keyboard (deprecated in favor of keydown and keyup).
submitFires when a form is submitted.
changeFires when the value of an <input>, <textarea>, or <select> element has been changed.
focusFires when an element gains focus (e.g., when a user clicks or tabs into an element).
blurFires when an element loses focus.
inputFires when the value of an <input> or <textarea> element is changed, even without losing focus.
resizeFires when the document view (window) has been resized.
scrollFires when the document view or an element is scrolled.
loadFires when the entire page (including images, scripts, etc.) has fully loaded.
DOMContentLoadedFires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
unloadFires when the document or a child resource is being unloaded.
dragFires continuously when an element is being dragged.
dropFires when a dragged element or text is dropped on a valid drop target.
contextmenuFires when the right mouse button is clicked (usually to open a context menu).
touchstartFires when a touch point is placed on the touch surface.
touchmoveFires when a touch point is moved along the touch surface.
touchendFires when a touch point is removed from the touch surface.
touchcancelFires when a touch event is interrupted, such as by an alert popping up.