lax.js
Simple & lightweight (<4kb gzipped) vanilla JavaScript library to create smooth & beautiful animations when you scroll.
Top Related Projects
Animate on scroll library
Reveal CSS animation as you scroll down a page
Animate elements as they scroll into view.
The javascript library for magical scroll interactions.
JavaScript animation engine
Quick Overview
Lax.js is a lightweight vanilla JavaScript library for creating smooth and beautiful animations when scrolling. It allows developers to easily add parallax effects and other scroll-based animations to web pages without the need for complex JavaScript or jQuery plugins.
Pros
- Lightweight and fast, with no dependencies
- Easy to implement and customize
- Supports various animation types and easing functions
- Works well on both desktop and mobile devices
Cons
- Limited documentation and examples
- May require additional CSS knowledge for complex animations
- Performance can be affected if too many elements are animated simultaneously
- Lacks advanced features found in some larger animation libraries
Code Examples
- Basic parallax effect:
<div class="lax" data-lax-translate-y="0 0, 400 -200">
Parallax Element
</div>
This code creates a simple parallax effect where the element moves up by 200 pixels as the user scrolls down 400 pixels.
- Opacity change on scroll:
<div class="lax" data-lax-opacity="0 1, 400 0">
Fade Out Element
</div>
This example makes an element fade out as the user scrolls down 400 pixels.
- Multiple animations combined:
<div class="lax"
data-lax-scale="0 1, 400 0.5"
data-lax-rotate="0 0, 400 360">
Scaling and Rotating Element
</div>
This code applies both scaling and rotation effects to an element as the user scrolls.
Getting Started
- Include the Lax.js library in your HTML file:
<script src="https://cdn.jsdelivr.net/npm/lax.js"></script>
- Initialize Lax in your JavaScript:
window.onload = function() {
lax.init()
// Add a driver that we use to control our animations
lax.addDriver('scrollY', function() {
return window.scrollY
})
}
- Add the
lax
class and data attributes to elements you want to animate:
<div class="lax" data-lax-translate-y="0 0, 400 -200">
Animated Element
</div>
- Customize animations using data attributes and adjust as needed.
Competitor Comparisons
Animate on scroll library
Pros of AOS
- Simpler setup and usage, with predefined animations
- Better browser compatibility, including older versions
- Extensive documentation and examples
Cons of AOS
- Less flexibility for custom animations
- Limited to scroll-based animations
- Larger file size compared to Lax.js
Code Comparison
AOS initialization:
AOS.init({
duration: 1000,
easing: 'ease-in-out',
once: true
});
Lax.js setup:
lax.init();
lax.addDriver('scrollY', function () {
return window.scrollY;
});
Key Differences
- AOS focuses on scroll-based animations with predefined effects
- Lax.js offers more customization and supports various animation triggers
- AOS has a larger community and more frequent updates
- Lax.js provides a smaller file size and potentially better performance
Use Cases
- Choose AOS for quick implementation of common scroll animations
- Opt for Lax.js when requiring complex, custom animations or performance optimization
Conclusion
Both libraries have their strengths. AOS is ideal for simple, scroll-based animations with broad browser support, while Lax.js excels in creating highly customized, performance-oriented animations. Consider your project requirements and target audience when selecting between the two.
Reveal CSS animation as you scroll down a page
Pros of WOW
- Simpler setup and usage, ideal for basic scroll animations
- Lightweight with no dependencies
- Better browser compatibility, including older versions
Cons of WOW
- Limited animation options compared to Lax.js
- Less flexibility for complex, custom animations
- No built-in parallax effects or advanced scrolling features
Code Comparison
WOW:
new WOW().init();
<div class="wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.5s">
Animated content
</div>
Lax.js:
lax.init();
lax.addElement('.selector', {
scrollY: {
translateY: [
["elInY", "elCenterY", "elOutY"],
[0, 'screenHeight/2', 'screenHeight'],
]
}
});
WOW focuses on simple class-based animations triggered by scrolling, while Lax.js offers more granular control over element properties and complex scroll-based animations. WOW is easier to implement for basic needs, but Lax.js provides greater flexibility for advanced animations and parallax effects. The code examples demonstrate the simplicity of WOW's setup compared to the more detailed configuration required for Lax.js.
Animate elements as they scroll into view.
Pros of ScrollReveal
- More mature and established project with a larger user base
- Extensive documentation and examples available
- Focuses specifically on scroll-based animations, making it easier to use for this purpose
Cons of ScrollReveal
- Limited to scroll-based animations, less versatile than Lax.js
- Larger file size compared to Lax.js
- Less customization options for complex animations
Code Comparison
ScrollReveal:
ScrollReveal().reveal('.headline', {
delay: 500,
distance: '50px',
origin: 'bottom',
duration: 1000
});
Lax.js:
lax.addElements('.headline', {
scrollY: {
translateY: [
["elInY", "elCenterY", "elOutY"],
[0, '-200', 0],
]
}
});
Both libraries offer simple ways to create scroll-based animations, but Lax.js provides more flexibility in defining custom animation behaviors. ScrollReveal's API is more focused on revealing elements with pre-defined animation options, while Lax.js allows for more complex, customizable animations based on scroll position and other parameters.
The javascript library for magical scroll interactions.
Pros of ScrollMagic
- More mature and feature-rich library with extensive documentation
- Supports complex animations and scene-based scrolling effects
- Integrates well with popular animation libraries like GSAP
Cons of ScrollMagic
- Steeper learning curve due to its comprehensive feature set
- Larger file size, which may impact page load times
- Less suitable for simple parallax effects or lightweight projects
Code Comparison
ScrollMagic:
var controller = new ScrollMagic.Controller();
var scene = new ScrollMagic.Scene({
triggerElement: "#trigger",
duration: 300
})
.setTween("#animate", {scale: 2})
.addTo(controller);
lax.js:
lax.init();
lax.addDriver("scrollY", function() {
return window.scrollY;
});
lax.addElements("#animate", {
scrollY: { scale: [1, 2] }
});
ScrollMagic offers more control over scene-based animations, while lax.js provides a simpler API for basic scroll-driven effects. ScrollMagic's approach is more verbose but allows for complex animations, whereas lax.js focuses on ease of use for common scroll interactions. The choice between the two depends on the project's complexity and specific animation requirements.
JavaScript animation engine
Pros of anime
- More comprehensive animation capabilities, including SVG and object property animations
- Larger community and ecosystem, with more resources and third-party plugins
- Better performance for complex animations due to its optimized engine
Cons of anime
- Steeper learning curve for beginners compared to lax.js
- Larger file size, which may impact load times for smaller projects
- Less focused on scroll-based animations, which is lax.js's specialty
Code Comparison
lax.js:
lax.addDriver('scrollY', function () {
return window.scrollY
})
lax.addElements('.selector', {
scrollY: {
translateY: [
["elInY", "elOutY"],
[0, 100],
]
}
})
anime:
anime({
targets: '.selector',
translateY: [0, 100],
easing: 'easeInOutQuad',
scrollTop: [0, 500],
duration: 1000
})
Both libraries offer ways to create scroll-based animations, but lax.js provides a more straightforward approach for this specific use case. anime offers more flexibility for general animations but requires more setup for scroll-based effects.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
lax.js
Simple & lightweight (<4kb gzipped) vanilla JavaScript library to create smooth & beautiful animations when you scroll.
What's new with Lax.js 2.0
Lax.js 2.0 has been completely re-written with a focus on modularity and flexibility giving you more tools to create awesome animations.
- New javascript animation syntax, allowing for more advanced effect combos
- Use any value to drive animations, for example mouse position, time of day .. and of course scroll!
- Animations can be given inertia when scrolling
- Create custom CSS bindings
- Animation easings
- And much more..
Examples
- Scroll effect
- Horizontal snap scroll
- Inertia
- Video/Gif playback
- Cursor position
- Text input
- Update HTML content
- Preset Explorer
Documentation
1. Getting started
2. Going deeper
3. Glossary
Getting started
NPM Setup
# https://www.npmjs.com/package/lax.js
npm install lax.js
yarn add lax.js
import lax from 'lax.js'
HTML setup
<script src="path-to-lax.min.js"></script>
<!-- or via CDN -->
<script src="https://cdn.jsdelivr.net/npm/lax.js" ></script>
Setup
To implement lax you need to create at least one driver, to provide values for animations, as well as the element animation bindings. Below is a simple example:
<!-- JS -->
<script>
window.onload = function () {
lax.init()
// Add a driver that we use to control our animations
lax.addDriver('scrollY', function () {
return window.scrollY
})
// Add animation bindings to elements
lax.addElements('.selector', {
scrollY: {
translateX: [
["elInY", "elCenterY", "elOutY"],
[0, 'screenWidth/2', 'screenWidth'],
]
}
})
}
</script>
<!-- HTML -->
<div class="selector">Hello</div>
Using presets
The easiest way to get started is to use presets via html classes. For example:
<div class="lax lax_preset_fadeIn:50:100 lax_preset_spin"></div>
Multiple presets can be chained together and they can be customised to suit your needs. Use the preset explorer to explore effects and see a simple example here.
DOM behavior and usage with Frameworks
To increase performance, lax.js
indexes the list of elements to animate when the page loads. If you're using a library like React, Vue or EmberJS, it is likely that you are adding elements after the initial window.onload. Because of this you will need to call lax.addElements
when you add components to the DOM that you want to animate, and lax.removeElements
when the component unmounts.
Please find a React example here. Other examples will be available soon for Vue.js and Angular.
Adding drivers
Drivers provide the values that drive your animations. To set up a driver just call lax.addDriver
with a name and a function which returns a number. This method is called every frame to calculate the animations so keep the method as computationally light as possible. The example below will be the most common use case for lax which returns the scrollY position of the window.
lax.addDriver(
'scrollY', // Driver name
function(laxFrame) {
return window.scrollY // Value method
},
{ } // Options
)
Driver options
inertiaEnabled: boolean = false
If enabled, the driver will calculate the speed at which its value is changing. Used to add inertia to elements using the inertia element option.
See this in action in the here.
frameStep: number = 1
By default each driver updates its value every animation frame, around ~60 times per second. You can use the frameStep
to reduce frequency of the driver value updating. For example a value of 2
would only update ~30 times per second and a value of 60
would only update about once per second.
Adding elements
You can add lax animations to an element using the addElements
method:
lax.addElements(
'.selector', // Element selector rule
{ // Animation data
scrollY: {
opacity: [
[0, 100],
[1, 0]
]
}
},
{
style: {} // Element options
}
)
Element options
style: StyleObject
Add static CSS to each element, for example:
{
transform: '200ms scale ease-in-out';
}
elements: Array<DOM nodes>
Pass references to raw DOM elements to allow for more flexible selection patterns. In this case, a unique selector
must still be passed as the first argument, however it does not need to be a valid DOM selector.
This allows the library to tag the elements for removal later. Example:
const myDomElements = $('.selector')
{
elements: myDomElements
}
onUpdate: (driverValues: Object, domElement: DomElement) => void
A method called every frame with the current driverValues and domElement. This could be used to toggle classes on an element or set innerHTML. See it in action here.
The driver values are formatted as follows:
{
scrollY: [ // Driver name
100, // Driver value
0 // Driver inertia
]
}
Going deeper
Custom animations
Custom animations are defined using an object.
// Animation data
{
scrollY: { // Driver name
translateX: [ // CSS property
['elInY', 'elOutY'], // Driver value map
[0, 'screenWidth'], // Animation value map
{
inertia: 10 // Options
}
],
opacity: [
// etc
]
}
}
Driver name
The name of the driver you want to use as a source of values to map to your animation, for example, the document's scrollY position. Read about adding drivers here.
CSS property
The name of the CSS property you want to animate, for example opacity
or rotate
. See a list of supported properties here.
Some CSS properties, for example
box-shadow
, require a custom function to build the style string. To do this use the cssFn element option.
Value maps
The value maps are used to interpolate the driver value and output a value for your CSS property. For example:
[0, 200, 800] // Driver value map
[0, 10, 20] // Animation value map
// Result
| In | Out |
| --- | --- |
| 0 | 0 |
| 100 | 5 |
| 200 | 10 |
| 500 | 15 |
| 800 | 20 |
Within the maps you can use strings for simple formulas as well as use special values. e.g:
['elInY', 'elCenterY-200', 'elCenterY',
See a list of available values here.
You can also use mobile breakpoints within driver value maps and animation maps for more flexibility.
scrollY: {
translateX: [
['elInY', 'elCenterY', 'elOutY'],
{
500: [10, 20, 50], // Screen width < 500
900: [30, 40, 60], // Screen width > 500 and < 900
1400: [30, 40, 60], // Screen width > 900
},
];
}
Options
modValue: number | undefined
Set this option to modulus the value from the driver, for example if you want to loop the animation value as the driver value continues to increase.
frameStep: number = 1
By default each animation updates its value every animation frame, around ~60 times per second. You can use the frameStep
to reduce frequency of the animation updating. For example a value of 2
would only update ~30 times per second and a value of 60
would only update about once per second.
inertia: number
Use to add inertia to your animations. Use in combination with the inertiaEnabled driver option.
See inertia in action here.
inertiaMode: "normal" | "absolute"
Use in combination with inertia
. If set to absolute
the inertia value will always be a positive number via the Math.abs
operator.
cssUnit: string = ""
Define the unit to be appended to the end of the value, for example
For example px
deg
cssFn: (value: number, domElement: DomElement) => number | string
Some CSS properties require more complex strings as values. For example, box-shadow
has multiple values that could be modified by a lax animation.
// Box-shadow example
(val) => {
return `${val}px ${val}px ${val}px rgba(0,0,0,0.5)`;
};
easing: string
See a list of available values here.
Optimising performance
Lax.js has been designed to be performant but there are a few things to bare in mind when creating your websites.
- Smaller elements perform better.
- Postion
fixed
andabsolute
elements perform best as they do not trigger a layout change when updated. - Off-screen elements do not need to be updated so consider that when creating your animation value maps.
- The css properties
blur
,hue-rotate
andbrightness
are graphically intensive and do not run as smoothly as the other available properties.
Glossary
CSS properties
name |
---|
opacity |
scaleX |
scaleY |
scale |
skewX |
skewY |
skew |
rotateX |
rotateY |
rotate |
translateX |
translateY |
translateZ |
blur |
hue-rotate |
brightness |
Special values
key | value |
---|---|
screenWidth | current width of the screen |
screenHeight | current height of the screen |
pageWidth | width of the document |
pageHeight | height of the document |
elWidth | width of the element |
elHeight | height of the element |
elInY | window scrollY position when element will appear at the bottom of the screen |
elOutY | window scrollY position when element will disappear at the top of the screen |
elCenterY | window scrollY position when element will be centered vertically on the screen |
elInX | window scrollX position when element will appear at the right of the screen |
elOutX | window scrollX position when element will disappear at the left of the screen |
elCenterX | window scrollX position when element will be centered horizontally on the screen |
index | index of the element when added using lax.addElements |
Supported easings
name |
---|
easeInQuad |
easeOutQuad |
easeInOutQuad |
easeInCubic |
easeOutCubic |
easeInOutCubic |
easeInQuart |
easeOutQuart |
easeInOutQuart |
easeInQuint |
easeOutQuint |
easeInOutQuint |
easeOutBounce |
easeInBounce |
easeOutBack |
easeInBack |
Top Related Projects
Animate on scroll library
Reveal CSS animation as you scroll down a page
Animate elements as they scroll into view.
The javascript library for magical scroll interactions.
JavaScript animation engine
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot