Home > Net >  Typescript - addEventListener type interface for scroll event
Typescript - addEventListener type interface for scroll event

Time:03-11

What is the correct way to add type interface when listening to scroll event.


    onMounted(() => {
      ...
      // Call when mounted;
    
      document.addEventListener("scroll", (e: ScrollEvent) => {
        console.log(e); // Type interface of ScrollEvent
      });
    });

CodePudding user response:

Below is an example, and here's the MDN page for Document: scroll event.

TS Playground

type Coords = {
  x: number;
  y: number;
};

function getScrollCoordinates (): Coords {
  return {
    x: window.scrollX,
    y: window.scrollY,
  };
}

function writeScrollCoordinates (elementContainer: HTMLElement, coords: Coords): void {
  elementContainer.textContent = JSON.stringify(coords, null, 2);
}

function handleScroll (event: Event): void {
  //                   ^^^^^^^^^^^^
  // The scroll event is just an instance of the base Event class
  writeScrollCoordinates(document.getElementById('coords')!, getScrollCoordinates());
}

window.addEventListener('scroll', handleScroll);

Example:

"use strict";
function getScrollCoordinates() {
    return {
        x: window.scrollX,
        y: window.scrollY,
    };
}
function writeScrollCoordinates(elementContainer, coords) {
    elementContainer.textContent = JSON.stringify(coords, null, 2);
}
function handleScroll(event) {
    //                   ^^^^^^^^^^^^
    // The scroll event is just an instance of the base Event class
    writeScrollCoordinates(document.getElementById('coords'), getScrollCoordinates());
}
window.addEventListener('scroll', handleScroll);
body {
  --size: 10000px;
  height: var(--size);
  width: var(--size);
}

#coords {
  font-family: monospace;
  font-size: 2rem;
  position: fixed;
  top: 1rem;
  left: 1rem;
}
<pre><code id="coords">Scroll to see coordinates</code></pre>

  • Related