Scroll-Activated Counting Effects with Vanilla JavaScript

Scroll-Activated Counting Effects with Vanilla JavaScript

Revolutionize Your Website with Scroll-Activated Counting Effects in JavaScript!

·

4 min read

Welcome to a new tutorial where we'll explore the fascinating world of scroll reveal effects by creating a counting animation using vanilla JavaScript. This effect will add a dynamic touch to your webpage, making the numbers come to life as the user scrolls down.

Demo:

Initialize the webpage with a HTML code.

In your HTML file, ensure you have elements with the "count" class. These could be any numeric elements you want to animate. For example:

<!-- Example HTML -->
<div class="count">100</div>
<div class="count">500</div>
<div class="count">1000</div>

Let's Start Animating

We opt for a class-based approach to manage the dynamic sizing of our Counting Elements, which directly correlates with the elements bearing the 'count' class. Utilizing classes enables us to effectively control and maintain distinct states for each element, offering a more organized and scalable solution.

Creation of Class "Count":

  1. Create class Count.

     class Count {
       constructor(final, element) {
         this.initial = 0;
         this.final = final;
         this.current = 0;
         this.element = element;
         this.increment = final / 200;
         this.isProcessing = false;
       }
     }
    

    In this constructor function:

    • final: Represents the target count value.

    • element: Represents the HTML element associated with the count.

    • initial: Holds the starting count value (initialized to 0).

    • current: Tracks the current count during animation.

    • increment: Calculated based on the target count to achieve a smooth animation.

    • isProcessing: Flags whether the counting animation is in progress.

  2. Start Method.

     class Count {
       // ... (constructor code)
    
       start() {
         this.interval = setInterval(() => {
           if (this.current < this.final) {
             this.current += this.increment;
             this.element.innerHTML = `${Math.round(this.current)}`;
           } else {
             clearInterval(this.interval);
             this.isProcessing = false;
           }
         }, 10);
       }
     }
    

    In the start method:

    • Initiates the counting animation using setInterval.

    • Increments the current count and updates the associated HTML element's content.

    • Clears the interval and flags completion when the final count is reached.

  3. Reset Method

     class Count {
       // ... (constructor code)
    
       reset() {
         this.isProcessing = false;
         this.current = 0;
         this.element.innerHTML = "0";
         if (this.interval) {
           clearInterval(this.interval);
         }
       }
     }
    

    The reset method:

    • Resets the counting animation.

    • Sets isProcessing to false.

    • Resets the current count and updates the associated HTML element's content to "0".

    • Clears the interval if it exists.

  4. Check And Update Method

     class Count {
       // ... (constructor code)
    
       checkAndUpdate() {
         if (!isElementOutOfView(this.element)) {
           if (!this.isProcessing) {
             this.isProcessing = true;
             this.start();
           }
         } else {
           this.reset();
         }
       }
     }
    

    In the checkAndUpdate method:

    • Calls the isElementOutOfView function to check if the associated HTML element is in view.

    • Initiates the counting animation using start if the element is in view and the animation is not already in progress.

    • Resets the animation using reset if the element is out of view.

This breakdown should provide a clear understanding of how the Count class operates step by step in the provided JavaScript code. Feel free to experiment and customize this class to fit your specific needs!

Define isElementOutOfView:
This function checks whether a given element is out of view by comparing its top position with the viewport's height. If the top position of the element is greater than the viewport's height (with a small buffer of 100 pixels), it is considered out of view.

function isElementOutOfView(element) {
  return (
    element.getBoundingClientRect().top >
    (window.innerHeight - 100 || document.documentElement.clientHeight - 100)
  );
}

Counting Object Setup:

const countAnimationElements = document.querySelectorAll(".count");

const CountingObjects = [];

countAnimationElements.forEach((element) => {
  CountingObjects.push(new Count(parseInt(element.innerHTML), element));
  element.innerHTML = "0";
});
  • Selects all elements with the "count" class using document.querySelectorAll.

  • Creates an array CountingObjects to store instances of the Count class for each element.

  • Initializes each Count object, pushing it to CountingObjects, and sets the initial HTML content of the element to "0".

Almost there! Now we just need to update each Count object when scrolling is detected. For that, we will create an Event Listener.

document.addEventListener("scroll", () => {
  updateCount();
});

function updateCount() {
  CountingObjects.forEach((obj) => {
    obj.checkAndUpdate();
  });
}

As you can see, updateCount function is called when a scroll event is triggered. This function iterates through each Count object in the CountingObjects array and calls the checkAndUpdate method which handles whether to start, reset, or continue the counting animation based on the element's visibility.

Source Code: GitHub

Conclusion

In summary, we've explored scroll-triggered counting effects using vanilla JavaScript. The Count class, at the core of this implementation, facilitates dynamic animations based on scroll position, offering a versatile solution for enhanced web interactivity. Experiment with these techniques in your projects for visually appealing features.

Happy coding!