Create scroll-based animation without JavaScript

Overview

Trigger JS

Build Status npm version npm downloads GitHub Stars Github Forks GitHub Open Issues License

Create scroll-based animation without JavaScript.

Sometimes we want to update the CSS style of an HTML element based on the scroll position, just like fast-forwarding or rewinding a video by scrolling up and down.

With Trigger JS, get the desired value with CSS variable on page scroll for your animation needed, without writing a single line of JavaScript code, configuration with HTML attributes. Checkout examples here.

Read this document in other languages: English, 繁體中文, 简体中文.

Getting Started

Method 1: Via CDN

  1. Include Trigger JS to your webpage with a script tag, with either CDN:

    • UNPKG CDN:
    ">
    <script src="//unpkg.com/@triggerjs/trigger" defer>script>
    • jsDelivr CDN:
    ">
    <script src="//cdn.jsdelivr.net/npm/@triggerjs/trigger" defer>script>
  2. Add tg-name to the DOM element that you want to monitor. The value of tg-name is the name of the CSS variable that binds to the element.

Hello, World
">
<div tg-name="scrolled" id="greeting">Hello, Worlddiv>

In the above example, CSS variable --scrolled is added to the selector #greeting:

<style>
  body {
    padding: 100vh 0; /* In order to make the page have enough room for scrolling */
  }

  #greeting {
    transform: translateX(
      calc(var(--scrolled) * 1px)
    ); /* Converts to px unit */
  }
style>
  1. Scroll the page and see the result.

Method 2: Build from source

  1. Get the library in either way:
    • From GitHub
    git clone https://github.com/triggerjs/trigger.git
    • From NPM
    npm i @triggerjs/trigger
  2. Change to the directory, install the dependencies:
    npm install
  3. There is a pre-built version bundle.js located in dist. Run a local web server and browse the greeting example in index.html :
    1. For example, type npx serve in the terminal
    2. Open up http://localhost:5000 in web browser.
    3. Scroll the page and see the result.
  4. The following command will build a new version to dist/bundle.js:
    • For development (with watch):
      npm run watch
    • For development:
      npm run build
    • For production:
      npm run prod

The tg- Attributes

Attribute Type Default Description
tg-name Required - The CSS variable name to store the value, with or without -- prefix.
tg-from Optional 0 The start value
tg-to Optional 1 The end value
tg-steps Optional 100 Steps to be triggered from tg-from to tg-to
tg-step Optional 0 Step per increment. If this value isn't 0, will override tg-steps.
tg-map Optional (Empty) Map the value to another value. Format:
- 1-to-1 mapping: value: newValue; value2: newValue2.
- Multiple-to-1 mapping: value,value2,value3: newValue.
- Range-to-1 mapping: value...value2: newValue.
tg-filter Optional (Empty) Only trigger if the scroll value is on the list. Format: 1,3,5,7,9. By default, the filter mode is retain. If we want to switch the mode to exact, add an ! at the end of the value. Read more about this in the dedicated section following.
tg-edge Optional cover Calculate the start and end of the scrolling effect. cover means off-screen to off-screen. The calculation starts in the appearance of the element at the bottom, and ends in the disappearance of element at the top; inset represents the calculation begins after the top edge of the element touches the top of the screen, ends when the bottom edge of the element reached the bottom of the screen. See below section for a diagram.
tg-follow Optional (Empty) Use the result calculated from another element. The value of tg-follow is the value of the target element's tg-ref. Caution: When tg-follow is set, tg-from, tg-to, tg-steps, tg-step and tg-edge are ignored in the same element.
tg-ref Optional (Empty) Define the name for other elements to reference using tg-follow.
tg-bezier Optional (Empty) Bezier easing setting, available values: ease, easeIn, easeOut, easeInOut, or custom numbers for a Cubic Bezier in format p1x,p1y,p2x,p2y.

Value Mapping

Number is not suitable for all the situations. For example, we want to update the text color based on the scroll value. the attribute tg-map can help.

The following example shows how to update the text color with the rules below:

Element Position (From the Bottom) Scroll Value Text Color
0% - 10% 1 black
10% - 20% 2 red
20% - 30% 3 orange
30% - 40% 4 yellow
40% - 50% 5 green
50% - 60% 6 cyan
60% - 70% 7 blue
70% - 80% 8 purple
80% - 90% 9 grey
90% - 100% 10 grey
Rainbow Text ">
<h1
  id="heading"
  tg-name="color"
  tg-from="1"
  tg-to="10"
  tg-steps="9"
  tg-map="1: black; 2: red; 3: orange; 4: yellow; 5: green; 6: cyan; 7: blue; 8: purple; 9,10: grey"
>
  Rainbow Text
h1>

<style>
  body {
    padding: 100vh 0; /* In order to make the page have enough rooms for scrolling */
  }

  #heading {
    color: var(--color);
  }
style>

Steps & Step

Let's say tg-from="200" and tg-to="-200", we want to move the element in x position with transform: translateX(). tg-steps lets us define how many steps from 200 to -200, for example, tg-steps="400" means run from 200 to -200 with 400 steps, 1 per increment; In other words, tg-steps="800" means 0.5 per increment.

But sometimes, we do not want to do the math by ourselves, that's why tg-step exists. tg-step defines the exact value of increment. Please note that if tg-step is defined, tg-steps will be ignored.

Noise Reduction

Sometimes we are only interested in certain values. For example, we only want to know when 25, 50, 75 show up from 0 to 100 (tg-from="0" and tg-to="100"). In this situation, tg-filter helps you.

Red (25), Yellow (50), Green (75) ">
<h1
  id="heading"
  tg-name="color"
  tg-from="0"
  tg-to="100"
  tg-step="1"
  tg-filter="25,50,75"
  tg-map="25: red; 50: yellow; 75: green"
>
  Red (25), Yellow (50), Green (75)
h1>

<style>
  body {
    padding: 100vh 0; /* In order to make the page have enough rooms for scrolling */
  }

  #heading {
    color: var(--color);
  }
style>

The mode of tg-filter

There are two modes for tg-filter, retain by default, the other one is exact. Here is an example to clarify this:

Trigger.js ">
<h1
  id="heading"
  tg-name="color"
  tg-from="0"
  tg-to="10"
  tg-step="1"
  tg-filter="5"
  tg-map="5: blue"
>
  Trigger.js
h1>

<style>
  body {
    padding: 100vh 0; /* In order to make the page have enough rooms for scrolling */
  }

  #heading {
    --color: black;
    color: var(--color);
  }
style>

In the above example, the text has an initial color of black, and it will turn to blue when it arrives at the middle of the page and never turn to black again because there is no trigger point of the black color.

So let's say we want the text color becomes blue only when the calculation value is 5, and becomes black for other values, We can change it to:

Trigger.js ">
<h1
  id="heading"
  tg-name="color"
  tg-from="0"
  tg-to="10"
  tg-step="1"
  tg-filter="4,5,6"
  tg-map="4: black; 5: blue; 6: black"
>
  Trigger.js
h1>

It works, but the code becomes redundant. To solve this, we can switch the filter mode to exact by adding an ! at the end of the value of tg-filter:

Trigger.js ">
<h1
  id="heading"
  tg-name="color"
  tg-from="0"
  tg-to="10"
  tg-step="1"
  tg-filter="5!"
  tg-map="5: blue"
>
  Trigger.js
h1>

In exact mode, --color becomes blue when the value is 5, and becomes the default when the value is not 5.

The design of adding ! to the value of tg-filter is the demand is exclusive to the attribute. Establishing another attribute for the mode is unnecessary or even leads to the misunderstanding.

Value Inheritance

Just like some CSS properties, the values of tg- attributes (except tg-follow, tg-ref) inherits from the parents if not being set in the current element. If we do not want it inherits from parent and set it as default value, just add the tg- attribute without value. For example:

">
<div tg-name="scale" tg-from="0" tg-to="50">
  <span tg-name="color" tg-to>
    
  span>
div>

tg-edge Explaination

The different between cover (default) and edge:

So that if tg-edge="inset", the element must be higher than the viewport (window.clientHeight).

JavaScript Event

We can also listen to the tg event on an element with JavaScript:

Trigger JS ">
<h1
  id="heading"
  tg-name="color"
  tg-from="1"
  tg-to="3"
  tg-steps="2"
  tg-map="1:#000;2:#666;3:#ccc"
>
  Trigger JS
h1>

<style>
  body {
    padding: 100vh 0; /* In order to make the page have enough room for scrolling */
  }

  #heading {
    color: var(--color);
  }
style>

<script>
  document.querySelector('#heading').addEventListener('tg', (e) => {
    console.log(e.detail); // {value: '#666'}
  });
script>

Customising the Prefix

If you are concerned with the tg- prefix that doesn't quite fulfill the standard of HTML5, it can be customised by the following setting in the body tag with data-trigger-prefix attribute:

Hello, World
">
<body data-trigger-prefix="data-tg">
  <div data-tg-name="scrolled" id="greeting">Hello, Worlddiv>
body>

The above example customises the prefix to data-tg. data-* is a completely valid attribute for putting custom data in HTML5.

Contribute

Feel free to fork this repository and submit pull requests. Bugs report in GitHub Issues, features/ideas/questions discuss in GitHub Discussions.

License

Trigger.js is MIT Licensed.

Comments
  • Also mention jsDelivr CDN in the guide

    Also mention jsDelivr CDN in the guide

    I remember unpkg CDN has a slow speed in the Chinese mainland. So I'd like to suggest also mentioning using the jsDelivr CDN in the guide. Besides the speed, it also supports fetching any public files from the GitHub repository. For example, we can get the latest built files from the default main branch through https://cdn.jsdelivr.net/gh/triggerjs/trigger/dist/bundle.js

    Here is the package in the jsDelivr CDN: https://www.jsdelivr.com/package/npm/@triggerjs/trigger

    opened by plainheart 2
  • fix: clean up activeElements after resize

    fix: clean up activeElements after resize

    https://github.com/triggerjs/trigger/blob/3831e957a54c4765defd40664adf31610aadecd3/src/trigger.js#L44-L54

    resize 事件里的 before hook 会不断的往 activeElements 添加重复元素,直到滚动事件发生

    opened by IronKinoko 1
  • Rewording README.zh-Hans.md

    Rewording README.zh-Hans.md

    更改部分表述至zh-Hans-CN下较为熟悉的说法。 部分表述没有更改,因为有一些不确定。比如:

    • 设置、设定:zh-Hans-CN下都有使用(以设置为主要),意思区分在计算机语境下似乎不大。作为名词主要用设置。
    • 文本、文字:zh-Hans-CN下都有使用,而zh-Hant似乎是不用文本的。部分情况下使用文本更符合语感,但强行替换的话结果可能有点奇怪。
    opened by lakejason0 1
  • Chore fixes

    Chore fixes

    1. rename tg-top & tg-height variables if the prefix is customized.
    2. avoid unnecessary calls on getPrefix function.
    3. simplify getPrefixSetting function & setPrefix function.
    4. remove unnecessary typescript as. (triggerjs/trigger#18)
    5. tweak some comments and correct some typos.
    opened by plainheart 0
  • refactoring: converted some mutable variables to constant, and more

    refactoring: converted some mutable variables to constant, and more

    I converted some mutable variables to constant because I think it's cleaner.

    Also, in the helpers.ts, there is no need to call valueOf explicitly because based on the function signature, parameter "number" is a number, not an object created with new Number(). please take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/valueOf#examples

    opened by ahhshm 0
  • Add autoformatting capabilities with existing `prettier` and new `husky` and `lint-staged` dev-dependencies

    Add autoformatting capabilities with existing `prettier` and new `husky` and `lint-staged` dev-dependencies

    I also add some types and doc comments.

    After git commit -m "some notes" executed, husky & lint-staged & prettier will auto format the source codes with prettier.config.js.


    我添加了一些类型和文档注释。

    在你 git commit 提交之后,husky、lint-staged 和 prettier 会共同作用进行自动代码格式化,格式化的配置文件是项目根目录下的 prettier.config.js.

    opened by onsummer 0
  • Remove unnecessary default value for parameter `hook`

    Remove unnecessary default value for parameter `hook`

    hook = {} is not necessary since there is a null/undefined check in the code.

    hook && typeof hook.before === "function" && hook.before();
    
    opened by plainheart 0
  • 【filter新增平滑参数@有个问题】如果filter和map指定刚好重复的话会返回异常的值

    【filter新增平滑参数@有个问题】如果filter和map指定刚好重复的话会返回异常的值

    这个功能有个问题,如果filter和map指定刚好重复的话会返回异常的值 例子

      <div
            class="lift-transition-sticky-content"
            tg-from="0"
            tg-to="100"
            tg-edge="cover"
            tg-name="position"
            tg-filter="0,50,100@"
            tg-map="0:50;50:0;100:0"
          ></div>
    

    50-100的值为0,但是最终渲染的会是50,因为map也指定了0的映射值 源码问题在这

    export function parseValues() {
     
     if (filter.values.length > 0 && !filter.values.includes(value)) {
          if (filter.mode === 'smooth') {
            let region = calcKeyFrameRegion(mapping, value);
           
            if (region.length) {
              // 这里获取的范围值是 0
              value = calcKeyFrameValue(mapping, value, region);
            } else {
              return;
            }
          } else {
            if (filter.mode === 'exact') {
              element.lastValue = null;
              el.style.removeProperty(name);
            }
            return;
          }
        }
      // 这里会根据value的值重新获取映射导致异常
       if (typeof mapping[value] !== 'undefined') {
          value = mapping[value];
        }
    
    }
    

    Originally posted by @RexYao97 in https://github.com/triggerjs/trigger/issues/28#issuecomment-1019912130

    opened by RexYao97 0
Releases(v1.0.8)
Owner
Trigger JS
A library for creating scroll-based animation with HTML attributes and CSS variables.
Trigger JS
JavaScript animation engine

anime.js JavaScript animation engine | animejs.com Anime.js (/ˈæn.ə.meɪ/) is a lightweight JavaScript animation library with a simple, yet powerful AP

Julian Garnier 44k Dec 30, 2022
Accelerated JavaScript animation.

Velocity beta NPM: npm install velocity-animate@beta Docs https://github.com/julianshapiro/velocity/wiki IMPORTANT: The velocityjs.org documentation r

Julian Shapiro 17.2k Jan 5, 2023
GreenSock's GSAP JavaScript animation library (including Draggable).

GSAP (GreenSock Animation Platform) Professional-grade animation for the modern web GSAP is a robust JavaScript toolset that turns developers into ani

GreenSock 15.5k Jan 8, 2023
CSS3 backed JavaScript animation framework

Move.js CSS3 JavaScript animation framework. About Move.js is a small JavaScript library making CSS3 backed animation extremely simple and elegant. Be

Sloth 4.7k Dec 30, 2022
🐿 Super easy and lightweight(<3kb) JavaScript animation library

Overview AniX - A super easy and lightweight javascript animation library. AniX is a lightweight and easy-to-use animation library with excellent perf

anonymous namespace 256 Sep 19, 2022
GreenSock's GSAP JavaScript animation library (including Draggable).

GSAP (GreenSock Animation Platform) Professional-grade animation for the modern web GSAP is a robust JavaScript toolset that turns developers into ani

GreenSock 15.4k Jan 5, 2023
Pure CSS (no JavaScript) implementation of Android Material design "ripple" animation

Pure CSS (no JavaScript) implementation of Android Material design "ripple" animation

Mladen Plavsic 334 Dec 11, 2022
Animate Plus is a JavaScript animation library focusing on performance and authoring flexibility

Animate Plus Animate Plus is a JavaScript animation library focusing on performance and authoring flexibility. It aims to deliver a steady 60 FPS and

Benjamin De Cock 5.9k Jan 2, 2023
Animation library that mimics CSS keyframes when scrolling.

Why Motus ? Motus allows developers to create beatuful animations that simulate css keyframes and are applied when the user scrolls. Features Node & B

Alexandru Cambose 580 Dec 30, 2022
React particles animation background component

particles-bg React component for particles backgrounds This project refers to the source code of the Proton official website, I packaged it into a com

lindelof 561 Dec 24, 2022
Theatre.js is an animation library for high-fidelity motion graphics.

Theatre.js is an animation library for high-fidelity motion graphics. It is designed to help you express detailed animation, enabling you to create intricate movement, and convey nuance.

Aria 8.6k Jan 3, 2023
Making Animation Simple

Just Animate 2 Making Animation Simple Main Features Animate a group of things as easily as a single thing Staggering and delays Chainable sequencing

Just Animate 255 Dec 5, 2022
Javascript library to create physics-based animations

Dynamics.js Dynamics.js is a JavaScript library to create physics-based animations To see some demos, check out dynamicsjs.com. Usage Download: GitHub

Michael Villar 7.5k Jan 6, 2023
Create beautiful CSS3 powered animations in no time.

Bounce.js Bounce.js is a tool and JS library for generating beautiful CSS3 powered keyframe animations. The tool on bouncejs.com allows you to generat

Tictail 6.2k Dec 30, 2022
Matteo Bruni 4.7k Jan 4, 2023
fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulate the page preloading effect.

What is fakeLoader.js fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulat

João Pereira 721 Dec 6, 2022
fullPage plugin by Alvaro Trigo. Create full screen pages fast and simple

fullPage.js English | Español | Français | Pусский | 中文 | 한국어 Available for Vue, React and Angular. | 7Kb gziped | Created by @imac2 Demo online | Cod

Álvaro 34.3k Dec 30, 2022
Animator Core is the runtime and rendering engine for Haiku Animator and the components you create with Animator

Animator Core is the runtime and rendering engine for Haiku Animator and the components you create with Animator. This engine is a dependency for any Haiku Animator components that are run on the web.

Haiku 757 Nov 27, 2022
It's a presentation framework based on the power of CSS3 transforms and transitions in modern browsers and inspired by the idea behind prezi.com.

impress.js It's a presentation framework based on the power of CSS3 transforms and transitions in modern browsers and inspired by the idea behind prez

impress.js 37k Jan 2, 2023