DEV Community

iDev-Games
iDev-Games

Posted on

1

πŸš€ Control Trig.js CSS Scroll Animations with JavaScript for Dynamic Direction Changes πŸ”„

Trig.js has already made scroll animations much easier and more flexible with the help of CSS variables. But what if we could take this a step further and add even more control? πŸ”§

In this post, we'll show you how you can leverage JavaScript to dynamically change the direction of a Trig.js animation based on scroll position! This combination of CSS variables and JS creates endless possibilities for creating interactive and advanced scroll effects that are both lightweight and performant. ⚑

Let’s break it down:

Codepen Example

πŸ› οΈ Setting Up Trig.js and CSS Variables

First, we need to set up Trig.js to handle the scroll animations. The magic happens with CSS variables that Trig.js generates to track the scroll position.

Here’s the basic setup:

Step 1: Install Trig.js

Add the script to your HTML to get started with Trig.js:

<script src="https://cdn.jsdelivr.net/npm/trig-js/src/trig.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Step 2: Add Data Attributes to Track Scroll Position

To track the scroll position and expose it as a CSS variable, we use the data-trig and data-trig-var attributes.

<div class="pinContainer" data-trig data-trig-var="true" data-trig-pixels="true" data-trig-min="-200" data-trig-max="100">
  <div class="pinned">
    <h1 id="title">TRIG.<span class="move">JS</span></h1>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

By using the data-trig-pixels attribute, we get a pixel-based scroll position, which allows us to control elements' movements based on the scroll.

Step 3: Animate with CSS Variables 🎨

Now, we can use the --trig and --trig-px variables to animate the element based on the scroll position. Here’s an example of translating the .move element on the X-axis:

.move {
  transform: translateX(calc(var(--trig-px) - 10px));
  transition: transform ease-out 0.3s;
  display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode

This will move the element horizontally as the user scrolls. But what if we want to reverse the direction once the scroll position reaches 50%? πŸ”„

πŸ”„ Adding JavaScript for Dynamic Direction Change

Now comes the fun part! We can use JavaScript to check the scroll position and dynamically change the direction of the animation based on the value of --trig.

JavaScript to Detect Scroll Direction πŸ“œ

We will write a function to monitor the --trig variable and add or remove a class when the scroll position crosses 50%. This class will reverse the animation direction.

// Function to check the value of --trig and apply the reverse class if necessary
function checkTrig() {
  const element = document.querySelector('.move');
  const trigValue = parseFloat(getComputedStyle(element).getPropertyValue('--trig')); // Get the --trig value as a percentage

  // If scroll position is 50% or more, add the 'reverse' class
  if (trigValue >= 50) {
    element.classList.add('reverse');
  } else {
    element.classList.remove('reverse');
  }

  // Use requestAnimationFrame to continuously check for scroll updates
  requestAnimationFrame(checkTrig);
}

// Start the checkTrig function
checkTrig();
Enter fullscreen mode Exit fullscreen mode

This code listens for the scroll position, and if the --trig value reaches 50%, it adds a .reverse class to the .move element, which changes its direction.

Adding the Reverse Class

When the .reverse class is added, we can use it to reverse the transform direction:

.move.reverse {
  transform: translateX(calc(var(--trig-px-reverse) + 100px));
}
Enter fullscreen mode Exit fullscreen mode

🎨 Check Out the Code in Action

This approach gives us complete control over our animations, enabling us to create more advanced, interactive scroll animations! You can experiment with the threshold for changing the direction or tweak other properties to create a variety of effects. πŸ’‘

πŸ‘‰ Here’s a live demo of this animation in action on CodePen:

Check it out on CodePen! 🎬


πŸ“ Why This Approach Works So Well

Trig.js provides an intuitive and lightweight solution for scroll animations using CSS variables, and by adding a small amount of JavaScript, we unlock even more advanced functionality! πŸ”‘

By utilizing CSS variables, we can dynamically control animations in a way that is both lightweight and scalable. And when we combine this with the power of JavaScript, we can fine-tune every detail of the animation. πŸ”§

This allows for performance-optimized scroll animations, free from the overhead of larger animation libraries. Whether you’re creating simple effects or more complex interactivity, Trig.js + JavaScript gives you the flexibility you need without the bloat. πŸš€

πŸ”— Resources


With Trig.js and a bit of JavaScript, you have the flexibility to create interactive, performance-optimized scroll animations that work for any project. Whether you’re just getting started or already an advanced developer, Trig.js is a fantastic tool to add to your arsenal! ✨

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay