Stellar.js - Documentation

What is Stellar.js?

Stellar.js is a lightweight, open-source JavaScript library that provides parallax scrolling effects for websites and web applications. It simplifies the process of creating visually engaging and immersive user experiences by allowing you to easily add parallax scrolling to any element on your page. Stellar.js works by intelligently adjusting the position of elements relative to the viewport as the user scrolls, creating a sense of depth and movement. It’s designed to be easily integrated into existing projects and requires minimal configuration.

Key Features and Benefits

Setting up the Development Environment

Before you begin working with Stellar.js, ensure you have a basic development environment set up. This typically includes:

Installation and Setup Guide

Stellar.js is easily integrated into your projects using a couple of methods:

1. Using a CDN:

The simplest way to include Stellar.js is by using a Content Delivery Network (CDN). Add the following <script> tag within the <head> of your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/stellar.js/1.0.0/jquery.stellar.min.js"></script>

Remember that this method requires jQuery to be included as well. You should include the jQuery library before the Stellar.js script. For example:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stellar.js/1.0.0/jquery.stellar.min.js"></script>

2. Using npm (Node Package Manager):

If you’re using npm for your project’s dependencies, install Stellar.js using the following command in your terminal:

npm install stellar.js

Then, import it into your JavaScript file:

import Stellar from 'stellar.js';

// Initialize Stellar.js (see usage examples below)

After Installation:

Once Stellar.js is included, you can initialize it on your elements by adding the class stellar to the container element and calling $.stellar() in your JavaScript code (for CDN method). For the npm method you will need to refer to the specific documentation of the installed library. Refer to the Stellar.js documentation for detailed usage examples and API reference. Remember to consult the updated documentation for the most current instructions and API.

Core Concepts

Parallax Effects

Stellar.js fundamentally relies on parallax effects to create the illusion of depth. Parallax is the displacement or difference in the apparent position of an object viewed along two different lines of sight, and is used here to simulate a 3D effect within a 2D webpage. As the user scrolls, elements with different parallax values move at different speeds relative to the viewport. Elements with a higher parallax value will move faster than those with a lower value, creating the sense that some objects are closer to the viewer than others. Stellar.js achieves this by manipulating the CSS transform property of elements, specifically using translate3d for optimal performance.

Scene and Layer Management

Stellar.js implicitly handles scene management. The entire page, or a specific container element with the class stellar, acts as the scene. Within this scene, individual HTML elements represent layers. These layers are independent and can be assigned individual parallax values or other properties, influencing how they react to scrolling. You don’t explicitly define scenes or layers—they’re implicitly managed by Stellar.js based on the HTML structure and the data-* attributes (or equivalent JavaScript configuration) applied to the elements. The data-stellar-ratio attribute is key to adjusting the movement speed of each layer.

Camera and Perspective Control

While Stellar.js doesn’t explicitly represent a camera in the traditional 3D sense, the concept of perspective is integral to its parallax effects. The viewport acts as the viewer’s perspective. By changing parallax values, you effectively control the perceived distance of elements from this viewport “camera.” The higher the data-stellar-ratio value (or equivalent JavaScript property), the further away the element appears, and the slower it moves relative to the viewport. Lower values make the element appear closer and move faster. You don’t directly manipulate a camera object but instead indirectly influence perspective by controlling the movement speed and position of elements.

Animation and Transitions

Stellar.js itself doesn’t provide built-in animation features beyond the parallax scrolling effect. To incorporate additional animations or transitions, you’ll need to use other JavaScript libraries or CSS animations alongside Stellar.js. Stellar.js provides the framework for the parallax movement; you can then layer on top of this other animation or transition effects using libraries like GSAP, Animate.css, or CSS transitions, triggered by scrolling events or other user interactions.

Event Handling

Stellar.js doesn’t directly expose a large range of custom events. However, you can leverage standard JavaScript event listeners to detect and respond to the parallax scrolling effect. For instance, you could use the scroll event to trigger additional actions or animations based on the scroll position. By monitoring the scroll position and correlating it with the parallax movement of elements, you can create complex interactions and animations synchronized with the parallax effect. Remember that overusing events might impact performance, especially on complex pages. Efficient event handling is crucial for a smooth user experience.

Working with Scenes

Creating and Configuring Scenes

In Stellar.js, a “scene” is implicitly defined by any element to which you apply the parallax effect. This is typically done by adding the class stellar to a container <div> element. This container element then becomes the root of your parallax scene. While there isn’t explicit scene creation, the configuration happens via the $.stellar() function (or its equivalent in the npm version) and any options passed to it. These options allow you to globally control aspects of the parallax effect within that scene, like horizontal parallax, vertical parallax, responsiveness, and more. For example, disabling horizontal scrolling might be configured via an option passed to $.stellar(). The entire subtree within the container with the stellar class will be affected.

Adding Layers to a Scene

Adding layers is simply a matter of adding HTML elements within the container element that has the stellar class. Each child element becomes a layer within the scene. The key to controlling the parallax effect on each layer is setting its data-stellar-ratio attribute. This attribute determines how fast the layer moves relative to the viewport during scrolling. A value of 1 means it moves at the same speed as the viewport, 2 means it moves twice as fast (in the opposite direction), 0.5 means it moves half as fast, and so on. You can also use data-stellar-horizontal-offset and data-stellar-vertical-offset attributes to position elements within the scene.

Managing Layer Properties

Layer properties are primarily controlled through custom data attributes on the HTML elements. These attributes include:

These attributes provide a declarative way to manage layer properties directly in your HTML. You can also programmatically control these properties using JavaScript, although this is less common for simple setups. Remember to use appropriate CSS for positioning and styling your layers effectively.

Scene Composition Techniques

Effective scene composition involves strategically arranging layers and their parallax properties to create depth and visual interest.

Scene Loading and Unloading

Stellar.js doesn’t explicitly define “loading” and “unloading” scenes in the sense of dynamically creating and destroying them. However, you can control when the parallax effect is active. The parallax effect begins when the $.stellar() function is called (or its equivalent in the npm version) on your designated container element. You can stop the parallax effect by calling $.stellar('destroy') on that same element. This effectively removes the parallax effects from the scene. You might use this functionality in situations where you want to temporarily disable parallax scrolling, for example, when an overlay is active, or when you transition to a different page section with different parallax behavior. Remember that any parallax effects will restart when you call $.stellar() again on that element.

Layer Manipulation

Creating and Positioning Layers

Layers in Stellar.js are simply HTML elements within the container element that has the stellar class applied. Creating layers involves adding standard HTML elements (e.g., <div>, <img>, <span>) inside this container. Positioning is handled through standard CSS techniques (e.g., position: absolute;, top, left, right, bottom, transform). Stellar.js itself doesn’t provide specific functions for creating or positioning layers; it uses standard HTML and CSS. The parallax effect then manipulates the position of these elements based on their data-stellar-ratio, data-stellar-vertical-offset, and data-stellar-horizontal-offset attributes.

Layer Transformation (Scaling, Rotation, Translation)

Stellar.js primarily handles translation (movement) of layers through its parallax effect. However, you can apply scaling, rotation, and other transformations using standard CSS transforms. For example, you can add CSS like transform: scale(1.2) rotate(10deg); directly to a layer’s style to scale it by 120% and rotate it 10 degrees. These CSS transformations will be applied in addition to the parallax translation handled by Stellar.js. You can also use JavaScript to dynamically modify these CSS transforms to create more complex animations and interactions synchronized with the scrolling.

Layer Visibility and Z-index

Layer visibility is controlled using standard CSS properties like visibility or display. You can show or hide layers using JavaScript by changing these properties. The z-index CSS property is crucial for controlling the stacking order of layers. Layers with higher z-index values will appear on top of layers with lower values. Properly managing z-index is essential for creating layered effects where certain elements appear in front of or behind others. Stellar.js itself doesn’t directly manage visibility or z-index; it relies on standard CSS mechanisms.

Layer Grouping and Parenting

Stellar.js doesn’t offer built-in layer grouping or parenting features. To group layers logically, use standard HTML techniques like nesting elements within <div> containers. This allows you to apply styles and transformations to groups of layers together. For example, you could group several related image layers within a parent <div> and apply a class to that parent to control the parallax behaviour for the whole group, using standard CSS selectors to affect all child layers. Remember that Stellar.js’s parallax effect affects each element individually based on its attributes; grouping only affects the CSS styles and positioning of those elements.

Advanced Layer Effects

Stellar.js primarily provides a basic parallax scrolling effect. To achieve more advanced layer effects, such as complex animations, transitions, or other visual enhancements, you should leverage other JavaScript libraries or CSS techniques in conjunction with Stellar.js. For instance, you can use libraries like GSAP (GreenSock Animation Platform) for complex animation sequences synchronized with the parallax scrolling. Remember that using many external libraries can increase the overall size and complexity of your project. Carefully consider the performance implications of adding significant layers of complexity beyond the core parallax functionality of Stellar.js.

Camera Controls

Camera Movement and Positioning

Stellar.js doesn’t provide explicit camera objects or direct camera control in the traditional 3D sense. The “camera” is implicitly represented by the viewport. The parallax effect simulates camera movement by changing the position of elements relative to the viewport as the user scrolls. You don’t directly move a camera; you control the apparent movement by adjusting the parallax values (data-stellar-ratio, data-stellar-horizontal-offset, data-stellar-vertical-offset) of the individual layers. The faster a layer moves relative to the viewport, the greater the illusion of camera movement.

Camera Zoom and Field of View

Stellar.js doesn’t offer direct zoom or field-of-view (FOV) control. To simulate zooming, you would typically use CSS transforms (e.g., transform: scale()) applied to layers or containers. Changing the scale of elements will create a visual effect similar to zooming. Similarly, to simulate changes in FOV, you’d need to adjust the size and position of elements and their parallax behavior to create the impression of a wider or narrower field of view. This would require careful manipulation of layer properties and CSS styles, and is not a direct feature of Stellar.js.

Custom Camera Controls

Since Stellar.js doesn’t have built-in camera controls, creating custom controls requires using JavaScript to manipulate layer properties dynamically. You would need to listen for user input events (e.g., mouse clicks, keyboard presses, touch gestures) and then programmatically update the data-stellar-ratio, data-stellar-horizontal-offset, and data-stellar-vertical-offset attributes of relevant layers. This level of customization allows for advanced interactions and non-standard parallax behaviors beyond simple scrolling-based parallax.

Camera Animations and Transitions

Creating camera animations requires combining Stellar.js with other JavaScript animation libraries (like GSAP) or CSS animations. You’d use JavaScript to change layer properties over time, creating smooth transitions and dynamic parallax effects. This might involve smoothly changing parallax ratios, offsets, or even CSS transforms (scale, rotation) to simulate camera movement and create cinematic effects. Stellar.js itself handles only the basic parallax based on scrolling; more advanced animations require external libraries.

Camera Event Handling

Stellar.js doesn’t expose specific “camera” events. However, you can use standard JavaScript event listeners (e.g., scroll, resize, mousemove) to track user interactions and trigger updates to your parallax scene. For example, you might listen to scroll events to update layer positions based on the scroll position and simulate smooth camera panning. Or you could use mousemove to link mouse movements to subtle camera adjustments. The events are standard JavaScript events; Stellar.js doesn’t provide specialized camera-centric events. Remember that efficient event handling is crucial for performance, especially when handling complex custom camera controls.

Animation and Interactions

Basic Animations

Stellar.js itself provides only the basic parallax scrolling animation. To create more complex animations, you must use additional JavaScript libraries or CSS animations. A simple example of a basic animation might involve changing the opacity of a layer as the user scrolls using JavaScript and CSS transitions. This can be triggered by an event listener that checks the scroll position. Stellar.js only provides the parallax movement; all other animation effects must be implemented separately.

Keyframe Animations

Keyframe animations, typically using CSS animations or libraries like Animate.css, can be synchronized with Stellar.js’s parallax scrolling. You define keyframes for different stages of an animation, and then trigger those animations based on scroll position or other events. For example, you might create a keyframe animation that changes the scale and rotation of a layer as the user scrolls past a specific section of the page. The key is to use JavaScript event listeners to detect the relevant scroll position and trigger the CSS animation.

Tweening and Interpolation

To create smooth transitions between animation states, you would typically use tweening libraries such as GSAP (GreenSock Animation Platform). GSAP provides powerful tools for creating sophisticated animations with easing functions, allowing you to precisely control the speed and timing of animation changes. You can use GSAP (or similar libraries) to animate changes to layer properties (position, opacity, scale, rotation, etc.) These animations can be synchronized with the Stellar.js parallax effect, creating seamless and visually appealing interactions.

Event-Driven Animations

Animations can be triggered by various events, including scroll events, mouse events (hover, click), and window resize events. You would use JavaScript event listeners to detect these events and start or stop animations accordingly. For instance, a hover event on a layer could trigger a scale animation, while scrolling past a certain point could trigger a fade-in animation. Remember to balance responsiveness with performance; excessive event listeners could negatively impact page performance.

Custom Animation Functions

For highly specialized animation requirements, you may need to write custom animation functions. These functions would likely use requestAnimationFrame for smooth animation and would directly manipulate CSS properties of elements using JavaScript. This approach gives you maximum control, but requires a more in-depth understanding of animation principles and JavaScript’s capabilities. You can integrate these custom animation functions with Stellar.js by triggering them based on scroll events or other user interactions, synchronizing them with the parallax scrolling. Well-structured custom functions will improve maintainability and readability of your animation code.

Advanced Techniques

Performance Optimization

Stellar.js is generally lightweight, but performance can become an issue with many layers or complex animations. Optimization strategies include:

3D Transformations and Rendering

While Stellar.js primarily works in 2D, you can create the illusion of 3D using CSS 3D transforms and perspective. This involves setting the perspective property on a parent container and using transform-style: preserve-3d on child elements. However, Stellar.js itself doesn’t directly handle 3D rendering. You will need to combine it with other techniques and potentially libraries to manage the complexities of 3D transformations and perspective. Complex 3D scenes will likely require more advanced techniques and potentially a more powerful library dedicated to 3D rendering.

Integration with Other Libraries

Stellar.js can be integrated with other JavaScript libraries to enhance functionality. Common integrations include:

Custom Shader Implementation

Stellar.js doesn’t directly support custom shader implementation. Custom shaders require WebGL and are generally used for advanced graphics rendering beyond the scope of Stellar.js’s capabilities. If you need advanced shader-based effects, you’d likely need a completely different approach using WebGL or a dedicated 3D graphics library. Stellar.js focuses on efficient 2D parallax scrolling and doesn’t provide an interface for custom shader manipulation.

Debugging and Troubleshooting

Debugging Stellar.js issues typically involves:

API Reference

Note: The Stellar.js API is relatively simple and primarily relies on data attributes in the HTML and standard JavaScript event handling. The following describes the conceptual structure of the objects and functions, but the exact implementation details may vary slightly depending on the version and whether you are using the CDN version or the npm package. The CDN version relies heavily on jQuery, whereas the npm version may have a different API structure. Consult the most up-to-date documentation for precise details.

Scene Object

Stellar.js doesn’t expose a dedicated “Scene” object in the traditional sense. A scene is implicitly defined by the element to which you apply the stellar class and call the initialization function ($.stellar() in the CDN version). The configuration options passed to the initialization function effectively configure the scene’s behavior. There are no methods to directly manipulate a “Scene” object as a distinct entity. The scene’s behavior is controlled indirectly by manipulating individual layers and their attributes.

Layer Object

Stellar.js does not expose a dedicated “Layer” object. Each layer is represented by an HTML element within the scene container. Layer properties are accessed and modified through the element’s data attributes (e.g., data-stellar-ratio, data-stellar-horizontal-offset, data-stellar-vertical-offset) or by directly manipulating the element’s CSS using JavaScript. There are no specific layer object methods provided by the Stellar.js library. The library works implicitly on the DOM elements themselves.

Camera Object

There is no “Camera” object in Stellar.js. The viewport acts as the camera. Camera effects are simulated by changing layer positions and parallax speeds. Any “camera” control is achieved by manipulating layer properties (through data attributes or direct DOM manipulation), not by directly controlling a camera object.

Animation Object

Stellar.js itself doesn’t provide a dedicated “Animation” object. Animations are implemented using external JavaScript libraries (like GSAP) or CSS animations. Stellar.js simply provides the parallax scrolling effect as a base upon which other animations are built using other libraries or direct DOM manipulation. Any animation-related functionality is entirely handled by the external libraries used, not by Stellar.js itself.

Utility Functions

The primary utility function in the CDN version is $.stellar(). This function initializes the parallax effect on the selected element. Depending on the version and implementation, additional functions may exist (for example, a destroy function to remove the parallax effect). The npm package version may offer a slightly different API or a more object-oriented approach, but the core functionality remains focused on initialization and handling the parallax effect based on data attributes and DOM manipulation. Refer to the library’s specific documentation for the exact functions available and their usage.

Examples and Tutorials

These examples assume you’ve included Stellar.js using a CDN or npm as described in the Installation and Setup Guide. Remember that the specific implementation might vary slightly based on whether you are using the CDN version which heavily relies on jQuery or the npm package which may use a different API. Always refer to the most current documentation for your specific version.

Basic Parallax Example

This example demonstrates a simple parallax effect with two layers: a background image and a foreground element.

<!DOCTYPE html>
<html>
<head>
<title>Stellar.js Basic Example</title>
<style>
body, html { height: 100%; margin: 0; }
#background { background-image: url('background.jpg'); height: 100%; background-size: cover; }
#foreground { position: absolute; bottom: 0; left: 0; width: 100%; }
</style>
</head>
<body>
<div id="background" class="stellar" data-stellar-background-ratio="0.5">
  <div id="foreground" data-stellar-ratio="1.5">Foreground Content</div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stellar.js/1.0.0/jquery.stellar.min.js"></script>
<script>
$(document).ready(function() {
  $('.stellar').stellar();
});
</script>
</body>
</html>

Replace 'background.jpg' with the actual path to your background image. The data-stellar-background-ratio attribute controls the background image’s parallax speed, while data-stellar-ratio controls the foreground element’s speed.

Complex Scene Example

This example illustrates a more complex scene with multiple layers and varying parallax speeds. You would add more <div> elements within the #container with different data-stellar-ratio and potentially offset values. Remember to style these elements with CSS to create the desired visual effect.

<div id="container" class="stellar">
  <div id="layer1" data-stellar-ratio="0.2"></div>
  <div id="layer2" data-stellar-ratio="0.5"></div>
  <div id="layer3" data-stellar-ratio="1.0"></div>
  <div id="layer4" data-stellar-ratio="2.0"></div>
</div>

You would then style each layer individually using CSS and possibly add more advanced effects using JavaScript libraries.

Custom Animation Example

This example uses GSAP to animate a layer’s opacity as the user scrolls. You’ll need to include the GSAP library.

$(document).ready(function() {
  $('.stellar').stellar();
  let tl = gsap.timeline();
  tl.to("#myLayer", { opacity: 0, scrollTrigger: { trigger: "#myLayer", start: "top 80%", end: "bottom 20%" } });
});

This assumes you have a <div id="myLayer"> element within your Stellar.js scene. The GSAP scrollTrigger will manage the animation based on the scroll position.

Interactive Scene Example

This example uses JavaScript to change a layer’s position based on mouse movement.

$(document).ready(function() {
  $('.stellar').stellar();
  $(document).mousemove(function(e) {
    let x = e.pageX / $(window).width() * 100;
    let y = e.pageY / $(window).height() * 100;
    $('#myLayer').css('left', x + '%');
    $('#myLayer').css('top', y + '%');
  });
});

This example requires a <div id="myLayer"> element within your scene and will reposition that layer dynamically as the mouse moves. You’ll need to handle the position within the bounds of the scene. This is just a basic example; you can greatly expand it for more sophisticated interactive effects. Remember that excessive event handling could impact performance.

Remember to replace placeholder elements and paths with your actual content and adjust the values as needed to achieve your desired effect. These are starting points; you can significantly expand upon them to create complex and visually stunning parallax scenes.

Troubleshooting and Support

Common Issues and Solutions

Debugging Tips

Community Support and Forums

While Stellar.js might not have a dedicated, large community forum, you can find support through general JavaScript or web development forums and communities (like Stack Overflow). Search for solutions to your specific problem; someone else may have encountered and solved a similar issue. Be sure to provide relevant details, including your Stellar.js version, browser, and any relevant code snippets when seeking help.

Contributing to Stellar.js

If you find a bug or want to add a feature, refer to the project’s repository (GitHub or other platform where the project is hosted) for contribution guidelines. Many open-source projects welcome contributions, especially bug fixes and improvements to documentation. Before contributing, check the project’s issue tracker to see if a similar issue has already been reported or addressed. Ensure your contributions adhere to the project’s coding style and standards.