Detect Something Changes In The Viewport – Tornis

Category: Javascript , Recommended | May 20, 2019
Author: robb0wen
Views Total: 158 views
Official Page: Go to website
Last Update: May 20, 2019
License: MIT


Detect Something Changes In The Viewport – Tornis


Tornis is a dependency-free JavaScript library to track the state of the viewport when you interact with the page.

Viewport states to track:

  • Mouse position
  • Mouse cursor velocity
  • Viewport size
  • Scroll position
  • Scroll velocity

How to use it:


$ npm install tornis --save

Import the Tornis API functions.

import { 
} from 'tornis';

Or directly include the tornis.js library from the dist folder.

<script src="/dist/tornis.js"></script>

Get the current viewport state using the getViewportState() function. This will return a state object like so:

  scroll: {
    changed: Boolean,
    left: Integer,
    right: Integer,
    top: Integer,
    bottom: Integer,
    velocity: {
      x: Integer,
      y: Integer
  size: {
    changed: Boolean
    x: Integer,
    y: Integer,
    docY: Integer
  mouse: {
    changed: Boolean,
    x: Integer
    y: Integer
    velocity: {
      x: Integer
      y: Integer

Track the state change in the viewport.

// define a watched function, to be run on each update
const updateValues = ({ size, scroll, mouse, orientation }) => {
  if (size.changed) {
    // do something related to size
  if (scroll.changed) {
    // do something related to scroll position or velocity

  if (mouse.changed) {
    // do something related to mouse position or velocity

// bind the watch function
// By default this will run the function as it is added to the watch list

// to bind the watch function without calling it
watchViewport(updateValues, false);

// when you want to stop updating

// to get a snapshot of the current viewport state
const state = getViewportState();

You Might Be Interested In:

Leave a Reply