Delay function from running until div is displayed on screen


At the bottom, there is a blue div with “Years of Service: 107” etc. This div uses a counting script, but by the time the user gets to it, it’s done. How can I delay this script to not run until it’s displayed on screen?

I’m using mdbootstrap and their “wow” script, which makes it invisible until displayed (for animation purposes), but that doesn’t keep the script from running at page load.

I’m sure this is easy to do, and I’m poking my way through the beginner jQuery class, but any specific help would be greatly appreciated.

The javascript is:

    $('.counter').each(function() { 
    	var $this = $(this), 
    		countTo = $this.attr('data-count'); 

    	$({ countNum: $this.text()}).animate({ 
    	countNum: countTo 
    	duration: 2500, 
    	step: function() { 
    	complete: function() { 

The HTML is:

<section id="counter" class="wow">
<div class="secondary-color p-1">
<div class="row">
<div class="col-md text-center p-4 lw-center">
<h3 class="white-text">Years of Service</h3>
<h1 class="white-text"><span class="counter" data-count="107">0</span></h1>
<div class="col-md text-center p-4 lw-center">
<h3 class="white-text">Business Partners</h3>
<h1 class="white-text"><span class="counter" data-count="300">0</span>+</h1>
<div class="col-md text-center p-4 lw-center">
<h3 class="white-text">Staff Experience</h3>
<h1 class="white-text"><span class="counter" data-count="323">0</span> Years</h1>

Thanks in advance for anyone willing to help a jQuery beginner. :slight_smile:


What you’d need to do in broad terms is to create a function that checks if an element is in the viewport or not (in this case the <section> containing the counter), then call that function every time the user scrolls the page. As soon as you detect that the counter is on the screen, you can start the counting script, then remove the original scroll handler, as you will presumably only want the counter to run once.

To get you started, there are a wide range of functions here to test if an element is visible in the viewport. The accepted answer seems to pretty much suit what you are looking for.

Why not take that and have a shot at implementing this functionality yourself, then let us know if you get stuck.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.