ScrollMagic is a JavaScript library that allows you to easily create compelling and engaging scroll-based animations and interactions on your website. It provides a simple and intuitive API to connect specific elements’ behavior to the user’s scroll position. This enables you to build impressive effects like parallax scrolling, animations triggered by scroll progress, sticky elements, and much more, all without complex JavaScript event handling or manual position calculations. ScrollMagic handles the complexities of viewport detection and element positioning, letting you focus on the creative aspects of your animations.
ScrollMagic offers several advantages over manual scroll-based animation implementations:
To use ScrollMagic, you first need to include the library in your project. You can download the library from the official website or use a CDN. Here’s how to include it using a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollMagic.min.js"></script>
After including the library, you can initialize a ScrollMagic controller. This controller manages the scenes and their interactions with the scroll position. A basic initialization looks like this:
let controller = new ScrollMagic.Controller();
This creates a new Controller
instance. The controller is the central hub for managing all your scroll-based animations. You’ll pass this controller instance to your scenes.
ScrollMagic revolves around three core concepts:
Controller: As explained above, the controller is the main object that manages the scenes and listens for scroll events. It keeps track of the current scroll position and updates the scenes accordingly. There’s typically only one controller per page.
Scene: A scene represents a single animation or effect triggered by the scroll position. Each scene is bound to a specific element on the page (the trigger element) and defines the animation to be played when the user scrolls the trigger into the viewport. A scene defines when the animation starts, how long it plays, and what kind of animation it uses.
Trigger: The trigger element is the HTML element whose position relative to the viewport determines when a scene’s animation should play. When the trigger element enters or leaves the viewport (or reaches a certain offset), the associated scene’s animation starts or ends. This can be any HTML element on your page.
These three components work together: The controller listens for scroll events. When a scroll event occurs, the controller checks the position of each scene’s trigger element. Based on the position, the controller triggers the animation associated with that scene. Scenes define the animation and how it should play, while the trigger defines the start/end conditions of the animation.
A Scene is the fundamental building block in ScrollMagic. It defines a specific animation or effect triggered by the scroll position. To create a new scene, you use the ScrollMagic.Scene()
constructor. The constructor accepts an object literal containing scene properties as arguments. At a minimum you’ll want to define a trigger element. For example:
let scene = new ScrollMagic.Scene({
triggerElement: "#myElement", //The element that triggers the scene
duration: 200 //Duration of the scene animation in pixels
})
This creates a scene that is triggered when the element with the ID “myElement” enters the viewport. We’ll explore the duration
parameter in more detail below. You then add the scene to the controller using controller.addScene(scene);
.
Several key properties configure a scene’s behavior:
triggerElement
: (String or HTMLElement) This is the most important property. It specifies the HTML element that acts as the trigger for the scene. When this element reaches a certain position relative to the viewport, the scene’s animation begins or ends. You can provide a CSS selector string (e.g., “#myElement”) or a direct reference to the DOM element.
duration
: (Number) This property determines the length of the scene’s animation in pixels. The animation will play over this distance as you scroll. A value of 0
will cause the animation to only occur at the trigger point. If you omit it or set it to a value <= 0 the scene will only execute once and will not have a duration.
offset
: (Number) This property adjusts the trigger position by a specified number of pixels. A positive offset moves the trigger point further down the page, and a negative offset moves it up. For example, an offset
of -100
means the animation will start when the top of the triggerElement
is 100 pixels above the top of the viewport. This is useful for fine-tuning the animation’s starting point.
Several properties describe a scene’s current state:
progress()
: This method returns a value between 0 and 1, representing the scene’s completion progress. 0 means the scene hasn’t started, and 1 means it’s fully completed. Values between 0 and 1 indicate the current progress of the animation.
state()
: This method returns a string representing the scene’s current state. Possible states include “BEFORE”, “DURING”, “AFTER”. These states correspond to different stages of the scene’s lifecycle.
Events: Scenes emit events as their state changes. You can listen for these events using the .on()
method. Common events include 'enter'
, 'leave'
, 'start'
, 'progress'
, and 'end'
. These allow you to execute code at specific points within the scene’s animation lifecycle. For example: scene.on('enter', function(){ /* code to run on scene enter */ });
Scenes provide several methods for managing their behavior:
addScene(scene)
: This method adds a scene to the controller.
remove()
: This method removes a scene from the controller.
setPin(element, pushFollowers)
: Pins the specified element to the viewport during the scene’s duration. pushFollowers
(boolean) controls whether elements below the pinned element should be moved to make space (true) or not (false).
setTween(tween)
: Associates a tweening animation (e.g., from GSAP or Tween.js) with the scene.
getProgress()
: Returns the scene’s current progress.
getState()
: Returns the scene’s current state.
update()
: Manually updates the scene’s state. Usually not necessary, as the controller automatically handles updates on scroll.
reverse()
: This method reverses the scene’s animation. If the animation is playing forwards, it will play backward, and vice-versa.
Reverse Order: By default, scenes are processed in the order they were added to the controller. If you need to control the order, you can change the order by removing and re-adding to the controller. More advanced solutions involve using the index
property when adding scenes to the controller. This will require more careful management of your scene instances.
A ScrollMagic controller is the central object that manages and orchestrates all your scenes. It listens for scroll events and updates the state of the scenes based on the scroll position. You create a controller using the ScrollMagic.Controller()
constructor. The simplest way to create a controller is:
let controller = new ScrollMagic.Controller();
This creates a new controller that observes vertical scroll events by default. We’ll explore the options for horizontal scrolling below.
The controller’s behavior can be customized through several properties, most notably:
vertical
: (boolean) This property (defaults to true
) determines whether the controller should listen to vertical scroll events. If set to false
, the controller will not respond to vertical scrolling.
horizontal
: (boolean) This property (defaults to false
) determines whether the controller should listen to horizontal scroll events. If set to true
, the controller will track horizontal scroll position instead of vertical. Note: Horizontal scrolling is less common and may have browser compatibility issues. You typically only enable one of vertical
or horizontal
.
You can configure these options when creating the controller:
let horizontalController = new ScrollMagic.Controller({ horizontal: true });
Controllers provide several essential methods for managing scenes:
addScene(scene)
: This method adds a scene to the controller. The scene will now be managed and updated by the controller. Scenes added later will be executed after those added earlier.
removeScene(scene)
: This method removes a scene from the controller’s management. The scene will no longer be updated, and its animations will cease to be triggered by scrolling.
update()
: Manually forces the controller to update the state of all its scenes. Generally, this is not necessary because the controller automatically updates itself on scroll events. However, it can be useful after significant DOM manipulations that might affect scene positions.
destroy()
: This method completely destroys the controller and removes all event listeners. It’s crucial to call this method if you’re dynamically removing or replacing the controller to prevent memory leaks.
While a single controller is sufficient for most projects, you can use multiple controllers to manage different sections or aspects of your page’s scroll-based interactions independently. For example, you might have one controller for the main page content and another for a specific sidebar.
Each controller maintains its own set of scenes and is independent of others. Creating multiple controllers is straightforward:
let controller1 = new ScrollMagic.Controller();
let controller2 = new ScrollMagic.Controller();
// Add scenes to controller1
let scene1 = new ScrollMagic.Scene({triggerElement: "#section1"}).addTo(controller1);
// Add scenes to controller2
let scene2 = new ScrollMagic.Scene({triggerElement: "#sidebar"}).addTo(controller2);
Remember that each controller needs its own set of scenes. This provides a flexible way to organize and manage complex scroll-based interactions on your web pages. Multiple controllers are particularly useful for sections that might have independent scrolling behaviors or when you want to precisely control the scope of your scroll animations.
ScrollMagic itself doesn’t perform animations; it acts as a trigger and manager for animations handled by other libraries. You connect your animation library’s animation to a ScrollMagic scene. The scene’s progress then controls the animation’s playback. This decoupling allows you to use your preferred animation library and leverage ScrollMagic’s scroll-based triggering capabilities. The core principle is to create an animation using your chosen library, then link it to a ScrollMagic scene using the setTween()
method.
ScrollMagic seamlessly integrates with many popular animation libraries, including TweenJS and GSAP (GreenSock Animation Platform). These libraries provide powerful animation capabilities, such as tweening, keyframes, and easing functions.
Example with GSAP:
// Assuming you have GSAP included in your project
let scene = new ScrollMagic.Scene({triggerElement: "#myElement"})
.setTween(TweenMax.to("#animatedElement", 1, {opacity: 0}))
.addTo(controller);
This code uses GSAP’s TweenMax.to()
method to create a tween that fades out the element with the ID “animatedElement” over one second. ScrollMagic will control the playback of this tween based on the scene’s progress.
Example with TweenJS:
//Assuming you have TweenJS included in your project
let scene = new ScrollMagic.Scene({triggerElement: "#myElement"});
let tween = createjs.Tween.get("#animatedElement").to({opacity: 0}, 1000); // 1000ms = 1 second
.setTween(tween).addTo(controller); scene
You can adapt this pattern to other animation libraries, but you’ll need to adjust the animation creation syntax according to the library’s API.
While using established animation libraries is recommended, you can also create custom animations using pure JavaScript. This gives you maximum control, but requires more manual effort. A custom animation function would update properties of target elements directly based on the scene’s progress()
value.
let scene = new ScrollMagic.Scene({triggerElement: "#myElement", duration: 300})
.on("progress", function (e) {
let progress = e.progress;
let element = document.getElementById("animatedElement");
.style.left = progress * 300 + "px"; // Example: move element horizontally
element
}).addTo(controller);
This example moves an element horizontally based on the scene’s progress. You can adapt this to create a wide range of custom effects.
ScrollMagic triggers animations based on the scroll position relative to the scene’s trigger element and duration. The animation starts when the trigger element enters the viewport (or a specified offset) and plays over the specified duration (or until complete if duration is 0). The animation’s progress is synchronized with the scroll position.
You can animate multiple elements within a single scene. Use the animation library’s functionality to target multiple elements within a single animation, and then pass this combined animation to the scene’s setTween()
method. For GSAP, this means selecting multiple elements in your tween definition.
Easing functions control the speed and rhythm of animations. Most animation libraries offer a wide variety of easing functions (linear, easeIn, easeOut, easeInOut, etc.). Select the easing function that best suits the desired effect within your chosen animation library. For example, in GSAP, you’d specify the ease
parameter in your TweenMax.to()
or similar method. This greatly enhances the visual appeal and control over the animation.
Scene pinning is a powerful technique that keeps an element fixed in the viewport while the user scrolls. This creates the effect of an element sticking to the screen, even as the rest of the page scrolls past. ScrollMagic’s setPin()
method simplifies this process.
let scene = new ScrollMagic.Scene({
triggerElement: "#pinTrigger",
duration: 300 //Height of the element to be pinned
}).setPin("#elementToPin")
.addTo(controller);
This code pins the element with the ID “elementToPin” to the viewport while the user scrolls past the element with the ID “pinTrigger”. The duration
should match the height of the element to be pinned. The pinned element will remain in place until the scene ends.
ScrollMagic scenes can modify an element’s position and appearance as the user scrolls. This goes beyond simple animations; you can dynamically change CSS properties, creating complex visual effects like parallax scrolling. You typically achieve this using the scene’s progress value and the animation library’s methods to update CSS transforms or other properties.
let scene = new ScrollMagic.Scene({triggerElement: "#parallaxTrigger", duration: 500})
.on("progress", function (e) {
let progress = e.progress;
let element = document.getElementById("parallaxElement");
.style.transform = "translateY(" + progress * -200 + "px)"; //Example: Parallax effect
element
}).addTo(controller);
This example creates a parallax effect, moving the element vertically based on scroll progress. Remember that transform properties are generally more performant than directly manipulating properties like top
and left
.
ScrollMagic’s strength is its flexibility to work with various animation libraries. You are not limited to GSAP or TweenJS; you can integrate it with any animation library that allows you to create and control animations programmatically. The key is to create the animation outside ScrollMagic and then pass it to the setTween()
method. Refer to the library’s documentation to understand how to create an animation and how to control its progress (pausing, resuming, seeking, etc.).
ScrollMagic offers a robust event system. You can attach callbacks to various events, allowing fine-grained control over animation behavior. This is crucial for creating complex interactions. Key events include:
'enter'
: Triggered when a scene’s progress becomes greater than 0.'leave'
: Triggered when a scene’s progress becomes 0 (after having been greater than 0).'start'
: Triggered when a scene begins.'progress'
: Triggered continuously as a scene’s progress changes.'end'
: Triggered when a scene completes.let scene = new ScrollMagic.Scene({triggerElement: "#myElement"})
.on("enter", function() { console.log("Scene entered"); })
.on("progress", function(e) { console.log("Progress:", e.progress); })
.addTo(controller);
These events provide opportunities to execute custom code at specific points in the scene lifecycle.
Debugging ScrollMagic issues involves checking several areas:
Correct Library Inclusion: Ensure that ScrollMagic and any animation libraries are correctly included in your project and loaded before initialization.
Scene and Controller Setup: Double-check the scene’s triggerElement
, duration
, and offset
properties, along with the controller’s initialization.
Element IDs and Selectors: Confirm that the selectors used in triggerElement
and setTween()
accurately target your HTML elements. Inspect the elements in the browser’s developer tools.
Browser Compatibility: Be aware of potential browser compatibility issues, particularly with older browsers or those that don’t fully support CSS transforms or specific animation libraries.
Console Logging: Use console.log
statements to track the values of scene properties (progress
, state
) and the events that are fired, helping you pinpoint issues in the scene’s lifecycle.
Conflict with Other Libraries: Check for potential conflicts with other JavaScript libraries that might interfere with ScrollMagic’s functionality.
GreenSock (GSAP) is a highly popular JavaScript animation library that integrates exceptionally well with ScrollMagic. GSAP’s TweenMax
(or gsap
in newer versions) and TimelineMax
provide powerful animation capabilities, making it an ideal choice for creating complex scroll-based effects.
To integrate GSAP with ScrollMagic, simply create your animations using GSAP and pass them to ScrollMagic’s setTween()
method:
// Assuming GSAP is included in your project
let scene = new ScrollMagic.Scene({triggerElement: "#myElement", duration: 300})
.setTween(gsap.to("#animatedElement", 1, {x: 200, ease: "power1.inOut"}))
.addTo(controller);
This code creates a GSAP tween that animates the #animatedElement
horizontally over one second. The ease
parameter specifies the animation easing. You can utilize GSAP’s features like timelines and complex animations effortlessly with ScrollMagic. Remember that GSAP’s API has evolved, so consult the current GSAP documentation for the most accurate usage.
ScrollMagic’s design facilitates integration with other JavaScript animation libraries. The key is to create your animation using the target library’s API and then pass the resulting animation object to ScrollMagic’s setTween()
method. Ensure your animation library supports pausing, resuming, and controlling the animation’s progress. If it doesn’t directly offer these controls, you might need to manage the animation manually using the progress
event of the ScrollMagic scene.
For example, with a hypothetical animation library called MyAnimLib
:
let myAnimation = MyAnimLib.animate("#myElement", {duration: 1000, properties: {opacity: 0}});
let scene = new ScrollMagic.Scene({triggerElement: "#myTrigger"})
.setTween(myAnimation)
.addTo(controller);
Remember to adapt the code based on your chosen library’s specific API and ensure its compatibility with ScrollMagic’s expectations.
Integrating ScrollMagic with popular JavaScript frameworks like React, Vue, and Angular requires careful consideration of component lifecycle and DOM manipulation. Here’s a general approach:
React: You’ll typically initialize the ScrollMagic controller and scenes within a useEffect
hook, ensuring the initialization occurs after the DOM is rendered. Manage scene cleanup within the useEffect
cleanup function to avoid memory leaks.
Vue: Use a mounted
lifecycle hook to initialize ScrollMagic and a beforeDestroy
hook for cleanup. Pay attention to how you access DOM elements within your Vue components, potentially using refs.
Angular: Initialize ScrollMagic within ngOnInit
and perform cleanup within ngOnDestroy
. Angular’s dependency injection and change detection mechanism may require extra care when dealing with DOM updates triggered by ScrollMagic.
Regardless of your framework, ensure that the triggerElement
and animated elements exist in the DOM before initializing ScrollMagic. You’ll often need to use refs or similar mechanisms to access DOM elements within the framework’s component structure.
Timing Issues: Animations might start too early or late. Verify that triggerElement
accurately selects the DOM element and that the offset
is correctly configured. Check if your animation library needs time to initialize before ScrollMagic uses it.
Animation Not Triggering: Double-check that the scene is added to the controller using addTo(controller)
. Inspect the browser’s console for errors or warnings.
DOM Element Not Found: Ensure the element selected by triggerElement
exists in the DOM when the scene is initialized. Use the browser’s developer tools to inspect the element.
Conflicts with Other Libraries: If other libraries manipulate the same elements, it may interfere with ScrollMagic’s operation. Try disabling other libraries temporarily to determine if they cause conflicts.
Framework-Specific Issues: In frameworks like React, Vue, and Angular, ensure correct DOM access within the component’s lifecycle methods. Proper cleanup (using componentWillUnmount
in React, beforeDestroy
in Vue, or ngOnDestroy
in Angular) is crucial to avoid memory leaks and unexpected behavior.
ScrollMagic is generally performant, but certain practices can significantly improve its efficiency, especially on complex projects or low-powered devices:
Minimize DOM manipulation: Avoid unnecessary DOM updates within your animation callbacks. Instead, perform as many calculations and transformations as possible before updating the DOM. Use CSS transforms (translate
, scale
, rotate
) whenever feasible; they are significantly faster than directly manipulating top
, left
, width
, etc.
Use efficient animation libraries: Libraries like GSAP are optimized for performance. Choose animation libraries known for their efficiency.
Limit the number of scenes: While ScrollMagic can handle many scenes, excessively large numbers can impact performance. Try to group similar animations if possible.
Optimize scene durations and offsets: Carefully plan scene durations and offsets to avoid redundant calculations. Use appropriate values that minimize the controller’s workload.
Avoid unnecessary event listeners: Only attach event listeners when strictly necessary. Remove event listeners when they are no longer needed (e.g., in component unmount methods in React/Vue/Angular).
Debounce or throttle events: If you are performing computationally expensive operations within event callbacks, consider debouncing or throttling these events to reduce the frequency of updates.
Lazy loading: For pages with many scroll-based animations, consider lazy loading the animations or the required assets only when they come into the viewport.
Modular design: Break down your code into smaller, well-defined functions and modules to enhance readability and maintainability.
Clear naming conventions: Use descriptive names for variables, functions, and scenes to improve code understanding.
Comments and documentation: Add comments to explain complex parts of your code. Clearly document the purpose and functionality of each scene and its associated animation.
Version control: Use Git (or another version control system) to manage your code and track changes effectively.
Testing: Implement unit tests and integration tests to ensure code correctness and prevent regressions.
Incorrect trigger element selection: Double-check that your triggerElement
selectors correctly target the intended elements. Use browser developer tools to confirm.
Overlapping scenes: Conflicting scenes can lead to unexpected behavior. Carefully plan the order and durations of your scenes to avoid overlap.
Unhandled events: Always handle potential errors or unexpected events. Implement error handling mechanisms to gracefully manage issues.
Memory leaks: Remove event listeners and destroy controllers when they are no longer needed, particularly in dynamic web applications. Properly clean up scenes and animations.
Performance bottlenecks: Profile your code to identify performance bottlenecks and address them through optimization techniques described earlier.
Keyboard navigation: Ensure your animations are accessible to users who navigate your site primarily with the keyboard. Avoid animations that might interfere with keyboard focus or make it difficult to interact with elements.
Screen reader compatibility: Test your animations with screen readers to ensure they do not interfere with screen reader functionality. Provide alternative text or descriptions for animated content where appropriate.
Epilepsy awareness: Be mindful of users with photosensitive epilepsy. Avoid rapidly flashing or strobing animations that could trigger seizures. Use appropriate color contrast and avoid overly jarring transitions.
Sufficient contrast: Ensure that animations maintain adequate color contrast throughout the process to remain visible and usable to people with visual impairments.
Alternative content: If the animation provides critical information, provide text-based alternatives or descriptions that convey the same information.
Parallax scrolling is a classic use case for ScrollMagic. It involves moving background elements at a slower rate than foreground elements as the user scrolls, creating a sense of depth and immersion.
let scene = new ScrollMagic.Scene({
triggerElement: "#parallax-section",
duration: 500, // Adjust duration to match section height
}).on("progress", function (e) {
let progress = e.progress;
document.getElementById("background").style.transform = `translateY(${progress * -100}px)`; // Background moves slower
document.getElementById("foreground").style.transform = `translateY(${progress * -50}px)`; // Foreground moves faster
}).addTo(controller);
This code creates a simple parallax effect. The background element moves half as fast as the foreground element. Adjust the -100
and -50
values to control the parallax effect’s intensity. Remember to style your background and foreground elements accordingly (#background
and #foreground
). This example uses CSS transforms for optimal performance.
ScrollMagic facilitates the creation of complex animations involving multiple elements, various animation libraries, and intricate interactions. You can orchestrate intricate sequences of animations triggered by scroll position changes. For example, you might combine GSAP tweens to create a complex animation of multiple elements appearing, moving, and changing properties in a coordinated way.
// Example using GSAP - requires GSAP to be included
let tl = gsap.timeline();
.to("#element1", 1, { x: 100 });
tl.to("#element2", 1, { opacity: 0 }, "<"); // Runs simultaneously with the previous tween.
tl.to("#element3", 1, { scale: 2 }, "<+=0.5"); //Delayed 0.5 seconds from previous.
tl
let scene = new ScrollMagic.Scene({triggerElement: "#complex-animation", duration: 600})
.setTween(tl)
.addTo(controller);
This example shows using a GSAP timeline to create a multi-element animation. Remember to adjust durations and delays as needed. This is easily expanded with more elements and complex animation sequences.
ScrollMagic can enhance interactive storytelling by revealing content incrementally as the user scrolls. This can create a more engaging and immersive experience for the reader. You could combine text reveal animations with image transitions and other visual elements, all synchronized with the scroll position.
//Example combining text and image reveals
let scene = new ScrollMagic.Scene({ triggerElement: "#story-section", duration: 500})
.on("progress", function(e){
let progress = e.progress;
document.getElementById("story-text").style.opacity = progress;
document.getElementById("story-image").style.opacity = progress;
}).addTo(controller);
This simple example reveals text and an image as the user scrolls. You can expand this significantly by using more sophisticated animations, incorporating different libraries, and introducing more complexity to the narrative.
ScrollMagic is an excellent tool for building visually engaging one-page websites. The different sections of the website can be animated and revealed as the user scrolls, creating a seamless and interactive user experience.
While ScrollMagic primarily reacts to the browser’s default scroll behavior, more advanced scenarios might require customizing scroll interactions. You would need to manually handle the scroll events to create unique scrolling experiences. This is significantly more complex than using ScrollMagic’s built-in functionalities and should be used only for highly customized situations. It often requires handling scroll events and directly manipulating the scroll position of elements, potentially overriding the browser’s default scrolling mechanism. This might involve using JavaScript to control the page’s scroll position, potentially in conjunction with libraries that provide smoother scrolling, such as smoothscroll.js. However, manipulating scroll behavior directly is generally discouraged due to the increased complexity, potential for performance issues, and compatibility problems across various browsers and devices. ScrollMagic’s built-in mechanisms are generally a preferable option.
This section provides a concise overview of the ScrollMagic API. For complete and up-to-date details, refer to the official ScrollMagic documentation.
The ScrollMagic
class is the namespace for all ScrollMagic functionality. It doesn’t have directly instantiable objects; instead, it serves as a container for the Scene
and Controller
classes, as well as utility functions. You primarily interact with it to create controllers and scenes.
The Scene
class represents a single animation or effect triggered by the scroll position.
Constructor:
new ScrollMagic.Scene(options)
options
(Object): An object containing scene configuration options:
triggerElement
(String or HTMLElement): The element that triggers the scene. Required.duration
(Number): The length of the scene’s animation in pixels. Defaults to 0.offset
(Number): Adjusts the trigger position by a specified number of pixels. Defaults to 0.triggerHook
(Number): Defines the position of the trigger element relative to the viewport at which the scene should begin. Values range from 0 (top of trigger element at the top of the viewport) to 1 (bottom of trigger element at the bottom of the viewport). Defaults to 0.5.Methods:
addIndicators(indicatorType)
: Adds visual indicators to the scene for debugging.addTo(controller)
: Adds the scene to a controller.on(eventName, callback)
: Attaches an event listener.off(eventName, callback)
: Detaches an event listener.remove():
Removes the scene from its controller.setPin(element, pushFollowers)
: Pins an element to the viewport.setTween(tween)
: Associates a tweening animation with the scene.getProgress()
: Returns the scene’s current progress (0-1).getState()
: Returns the scene’s current state (“BEFORE”, “DURING”, “AFTER”).update()
: Manually updates the scene’s state.reverse()
: Reverses the scene’s animation.The Controller
class manages scenes and listens for scroll events.
Constructor:
new ScrollMagic.Controller(options)
options
(Object): Controller configuration options:
container
(HTMLElement): The element to listen for scroll events on. Defaults to window
.vertical
(boolean): Whether to listen for vertical scroll events. Defaults to true
.horizontal
(boolean): Whether to listen for horizontal scroll events. Defaults to false
.Methods:
addScene(scene)
: Adds a scene to the controller.removeScene(scene)
: Removes a scene from the controller.update()
: Manually updates the controller’s state and all its scenes.destroy()
: Destroys the controller and removes all event listeners.scrollTo(position)
: Scrolls to a specific position.info()
: Returns information about the controller’s state.ScrollMagic uses a standard event system. Scenes and controllers emit events at various stages of their lifecycle. You attach event listeners using the .on()
method and remove them with .off()
. Common events include:
'enter'
, 'leave'
, 'start'
, 'progress'
, 'end'
'change'
, 'update'
ScrollMagic provides several utility functions within its namespace:
ScrollMagic.Scene.ease
: Provides easing functions for animations.ScrollMagic.Util.getScrollTop()
: Gets the current vertical scroll position.ScrollMagic.Util.getScrollLeft()
: Gets the current horizontal scroll position.ScrollMagic.Util.isMobile()
: Detects if the current device is a mobile device.This is a summarized overview. Always refer to the official ScrollMagic documentation for the most up-to-date and detailed API reference.