Introduction to ScrollMagic
ScrollMagic is a powerful JavaScript library for creating dynamic and engaging scrolling animations on web pages. With an extensive set of APIs, ScrollMagic makes it easier for developers to build captivating scroll-based interactions. In this article, we delve into the core functionalities of ScrollMagic and explore various API examples to help you get started.
Getting Started
To use ScrollMagic, you first need to include the ScrollMagic library in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollMagic.min.js"></script>
Basic ScrollMagic Scene
Here’s a simple example of creating a basic scene that triggers a class toggle:
<script> var controller = new ScrollMagic.Controller(); var scene = new ScrollMagic.Scene({ triggerElement: '#trigger', duration: 300 }) .setClassToggle('#animate', 'visible') .addTo(controller); </script>
Pinning an Element
To pin an element during scroll, you can use the following code:
<script> var controller = new ScrollMagic.Controller(); var scene = new ScrollMagic.Scene({ triggerElement: '#pin' }) .setPin('#pin') .addTo(controller); </script>
Setting ScrollMagic Indicators
For debugging and visualizing your scenes, ScrollMagic provides indicators:
<script src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/plugins/debug.addIndicators.min.js"></script> <script> var controller = new ScrollMagic.Controller(); var scene = new ScrollMagic.Scene({ triggerElement: '#trigger-2', duration: 200 }) .setClassToggle('#animate-2', 'visible') .addIndicators() // add indicators (requires plugin) .addTo(controller); </script>
Build an Application with ScrollMagic
Using the above APIs, let’s create a simple app where elements appear with animations as you scroll:
<script> var controller = new ScrollMagic.Controller(); // Scene 1: Toggle class when trigger enters viewport new ScrollMagic.Scene({ triggerElement: '#section1' }) .setClassToggle('#section1', 'visible') .addTo(controller); // Scene 2: Pin an element new ScrollMagic.Scene({ triggerElement: '#section2', duration: '100%' }) .setPin('#section2') .addTo(controller); // Scene 3: Add indicators for debugging new ScrollMagic.Scene({ triggerElement: '#section3', duration: 300 }) .setClassToggle('#section3', 'visible') .addIndicators() .addTo(controller); </script>
With these examples, you can start creating rich scrolling experiences for your web applications using ScrollMagic. Happy coding!
Hash: 895ffc9bb5c9634de1f5e84355a67fa948648490446a136053333f45bcc9ebba