Skip to content

Javascript library to apply css custom properties depending on the scroll position

License

Notifications You must be signed in to change notification settings

oom-components/scroll-styles

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

@oom/scroll-styles

Javascript library to apply css custom properties depending on the scroll position, allowing to create scrolling efects like parallax. It has the following features:

  • No dependencies
  • Superlight
  • High performance
  • Follows the progressive enhancement strategy
  • Built with ES6, so you may need a transpiler for old browser support

It's inspired by basicScroll library but lighter and with better performance, in order to be more flexible and customizable.

Install

Requirements:

npm install @oom/scroll-styles

Usage

import Scroll from './vendors/@oom/scroll-styles/src/scroll.js';

const scroll = new Scroll();

//Register an element to observe
const element = document.querySelector('.parallax');

scroll.observe(element, {
    name: '--scale',  // Name of the custom property
    element: [0, 1],  // [from, to] element intersection (0 = top, 1 = bottom, 0.5 = middle, etc)
    viewport: [1, 0]  // [from, to] viewport intersection
    media: '(min-width: 500px)'  // Observe only while this media-query is true

    //Custom handler, if you want to do more things that just update the property
    handler(element, scale, options) {
        element.style.setProperty(options.name, scale);
    }
})

//Remove an element
scroll.unobserve(element);

//Remove all elements
scroll.disconnect();

The --scale variable is a float number between 0 and 1, so you can use it in the css code:

.parallax {
    /* Use the value as is */
    opacity: var(--scale, 1);

    /* Use calc() to convert to other units */
    transform: translateY(calc(var(--scale, 1) * 50rem));
}

Demo

To run the demo, just clone this repository, enter in the directory and execute:

npm install
npm start

You should see something in http://localhost:8080/

There's an online demo here: https://oom-components.github.io/scroll-styles/

About

Javascript library to apply css custom properties depending on the scroll position

Topics

Resources

License

Stars

Watchers

Forks