Giter Site home page Giter Site logo

virtual-scroll's Introduction

virtual-scroll

A 2kb gzipped low-level library to create custom scrollers with touch and keyboard support. This is heavily inspired by Bartek Drozdz VirtualScroll util. See his article for reference.

Features

  • Can create multiple instances with different elements as targets
  • Let you do the actual scrolling logic: use CSS Transforms, WebGL animation or anything you like
  • Native arrow keys support and shift/space support mimicking default browser behaviour

For high-level libraries based off virtual-scroll, check locomotive-scroll or smooth-scrolling.

Installation

npm i virtual-scroll -S

Usage & API

Constructor

  • new VirtualScroll(options)
    • el: the target element for mobile touch events. Defaults to window.
    • mouseMultiplier: General multiplier for all mousewheel (including Firefox). Default to 1.
    • touchMultiplier: Mutiply the touch action by this modifier to make scroll faster than finger movement. Defaults to 2.
    • firefoxMultiplier: Firefox on Windows needs a boost, since scrolling is very slow. Defaults to 15.
    • keyStep: How many pixels to move with each key press. Defaults to 120.
    • preventTouch: If true, automatically call e.preventDefault on touchMove. Defaults to false.
    • unpreventTouchClass: Elements with this class won't preventDefault on touchMove. For instance, useful for a scrolling text inside a VirtualScroll-controled element. Defaults to vs-touchmove-allowed.
    • passive: if used, will use passive events declaration for the wheel and touch listeners. Can be true or false. Defaults to undefined.
    • useKeyboard: if true, allows to use arrows to navigate, and space to jump from one screen. Defaults to true
    • useTouch: if true, uses touch events to simulate scrolling. Defaults to true

Methods

  • instance.on(callback, context) Listen to the scroll event using the specified callback and optional context.

  • instance.off(callback, context) Remove the listener.

  • instance.destroy() Remove all events and unbind the DOM listeners.

Events note: Each instance will listen only once to any DOM listener. These listener are enabled/disabled automatically. However, it's a good practice to always call destroy() on your VirtualScroll instance, especially if you are working with a SPA.

Event

When a scroll event happens, all the listeners attached with instance.on(callback, context) will get triggered with the following event:

{
	x, // total distance scrolled on the x axis
	y, // total distance scrolled on the y axis
	deltaX, // distance scrolled since the last event on the x axis
	deltaY, // distance scrolled since the last event on the y axis
	originalEvent // the native event triggered by the pointer device or keyboard
}

Example

import VirtualScroll from 'virtual-scroll'

const scroller = new VirtualScroll()
scroller.on(event => {
	wrapper.style.transform = `translateY(${event.y}px)`
})

License

MIT.

virtual-scroll's People

Contributors

antinomy-studio avatar ayamflow avatar baptistebriel avatar cwervo avatar dmnsgn avatar hum-n avatar philipyoungg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

virtual-scroll's Issues

Edge Bug

Do you try this on Microsoft Edge?
seems don't work

Example Next.js Typescript Hook

Hey, just leaving this Issue here for anyone wanting to write this as a Next.js Typescript hook.

  1. In src/support.js, make sure to check for process.browser or you'll get a document is undefined error. This is due to SSR, I think.
const getSupport = () => {
  if (process.browser) {
    return {
      hasWheelEvent: "onwheel" in document,
      hasMouseWheelEvent: "onmousewheel" in document,
      hasTouch: "ontouchstart" in document,
      hasTouchWin: navigator.msMaxTouchPoints && navigator.msMaxTouchPoints > 1,
      hasPointer: !!window.navigator.msPointerEnabled,
      hasKeyDown: "onkeydown" in document,
      isFirefox: navigator.userAgent.indexOf("Firefox") > -1,
    }
  }
}

export default getSupport
  1. Hook :
import VirtualScroll from "libs/virtual-scroll/src/index"
import { useEffect, MutableRefObject } from "react"

export type VirtualScrollEvent = {
  x: number // total distance scrolled on the x axis
  y: number // total distance scrolled on the y axis
  deltaX: number // distance scrolled since the last event on the x axis
  deltaY: number // distance scrolled since the last event on the y axis
  originalEvent: Event // the native event triggered by the pointer device or keyboard
}
type VirtualScrollCallback = (e: VirtualScrollEvent) => void

const useVirtualScroll = (
  ref: MutableRefObject<HTMLElement>,
  callback: VirtualScrollCallback,
  dependencies: any = [],
) => {
  useEffect(() => {
    if (ref.current) {
      const instance = new VirtualScroll(ref.current)
      instance.on((e: VirtualScrollEvent) => callback(e))

      return () => {
        instance.destroy()
      }
    }
  }, dependencies)

  return typeof window !== "undefined"
}

export default useVirtualScroll
  1. Usage:
import useVirtualScroll, { VirtualScrollEvent } from "hooks/useVirtualScroll"

const HomeView: FC<Props> = ({ home, descriptionContent }) => {
  const testRef= useRef(null)
  const onVirtualScroll = (e: VirtualScrollEvent) => {
    console.log(e)
  }
  useVirtualScroll(testRef, onVirtualScroll, [testRef.current])

  return (
    <div ref={testRef}></div>
  )

Ivy compiler compatibility

Are you planning to add support for Ivy compiler?
Currently in Angular 13+ we need to do npm i --force to make this package work.

Thank you,
Shiva

Roadmap

  • make it work ๐Ÿ‘
  • add support for real scrollbar
  • fallback without scrollbar on iOS<8 & stuff

Broken when scroll back to top

Hi,

It seems that if I scroll down the page, VirtualScroll is working fine, by applying the inline transform to the wrapper.

However, if I scroll back up to the top of the page after previously scrolling downward, for some reason the inline transform value on the wrapper just keeps decreasing infinitely (see screenshot). This inline value just keeps adjusting itself, despite no scroll movement.

Screenshot 2019-03-21 at 12 29 19

Thank you in advance!

VirtualScroll is not defined

I'm getting " VirtualScroll is not defined " on

VirtualScroll.on(function(e) { .... <-- This line
// Code here
}

Running ES6

What have I missed?

Compiled script in npm registry

It would be nice to have access to a compiled version of this repo to be able to import in CDNJS.
At the moment, src/index.js cannot be imported by CodePen or JSFiddle because it cannot resolve his dependencies.

Thanks

Fake Scrollbar with `scroll` event?

Any idea how I would add a fake scroll bar which has the same functionality as a normal one (move scrollbar thumb, scroll content on scrollbar drag)?

I already have the fake scrollbar implemented which will be animated in the requestAnimationFrame to the same value as the content. But then I can't drag the scrollbar because it will be immediately updated by the requestAnimationFrame .

Would be nice to have a hint or an example. :)
Thanks!

Integration with GSAP ScrollTrigger

Hi,

I tried to implement it with gsap, following are my feelings:
1- There is no demo.
2- It felt quite choppy or not smooth at all. It's like I am jumping just 120px.
3- How to integrate it with GSAP and ScrollTrigger.
4- There is a destroy event to call on page switch when using SPA. But I don't see the option to update it or enable it for the next page like with other libraries.

Regards
Shehzad Asif

IE Edge trackpad problem

the virualscroll don't work with trackpad on IE Edge, dou you have an idea ? or its a known bug ?
Thx a lot for your work

Add option to disabled keyboard control

Hi and thx for your work,
I think to have the possibility to disabled keayboard control will be usefull for some project.
(put a keyStep option to 0 do the job for me)
Thx

Issue with mobile device

I have this site

mirror.studiomonocromo.it/it/about

seems that with mobile device android the page don't scroll down, why?

Cheers

Issue on Firefox with trackpad

I realized this because of using locomotive scroll and thought the issue is there, but they use virtual-scroll and for me it looks like the issue lays in following line:

evt.deltaY = e.wheelDeltaY || e.deltaY * -1

Basically, if I'm in Firefox and using a trackpad, the scrolling is way too fast.

if I only use
evt.deltaY = e.deltaY * -1;
instead of
evt.deltaY = e.wheelDeltaY || e.deltaY * -1;

it looks like it's the same behaviour as in chrome again, so maybe somethin inside Firefox changed regarding wheelDeltaY or something

Start Scroll Event

Hi and thx for your work.
I need a bullet proof "start scroll event" for my scroll implementation, do you have any idea to simulate this ?
Thx

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.