execute a jQuery number counter when scrolling is detected

My jQuery number counter is working perfectly, but it starts running as soon as the page loads. I'm trying to figure out how to make it run only when the element comes into view. Here is my current code:

EDIT

After some tinkering, I achieved the desired effect using waypoints. Here's the updated jQuery code:

   $('#counter').waypoint(function (direction) {
    $('.count').each(function () {
      var $this = $(this);
      jQuery({
        Counter: 0
      }).animate({
        Counter: $this.text()
      }, {
        duration: 2000,
        easing: 'swing',
        step: function () {
          $this.text(Math.ceil(this.Counter));
        }
      });
    });
  }, {
    offset: '80%'
  });
 #counter {
      position: relative;
      color: #fff;
      margin-top: 600px;
    }
    
    .counters {
      padding: 100px 0;
      width: 33.333%;
      float: left;
    }
    
    #counter-1 {
      background: #393939;
    }
    
    #counter-2 {
      background: #494949;
    }
    
    #counter-3 {
      background: #595959;
    }
    
    .line-numbers {
      text-align: center;
      display: block;
      font-size: 55px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="counter">
        <div id="counter-1" class="counters">
          <span class="line-numbers count">2000</span>
        </div>
        <div id="counter-2" class="counters">
          <span class="line-numbers count">2500</span>
        </div>
        <div id="counter-3" class="counters">
          <span class="line-numbers count">150</span>
        </div>
      </section>

Answer №1

If you need to determine if an element is within the viewport, you can utilize the following JavaScript function:

function checkIfElementIsVisible(elem) {
    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= viewportBottom) && (elemTop >= viewportTop));
}

This code implementation was referenced from this stackoverflow answer.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving data returned by PHP in an AJAX call

I am currently working on storing data from an ajax (jquery) response into a variable so that I can utilize it later in my code. Below is the jQuery code snippet: $(document).ready(function () { $("#submitReg").click(function () { var email = $(" ...

Just starting out with JS, curious if it's possible to transform these circles into diamonds instead

My goal is to transform this animated field of blinking circles into rectangles or diamonds, whichever is easier. Link: http://jsfiddle.net/Jksb5/1/ HTML <canvas id="pixie"></canvas> JS var WIDTH; var HEIGHT; var canvas; var con; var g; va ...

Execute the function as soon as the DIV enters the visible portion of the browser using jQuery

I am looking to trigger certain actions when a specific div comes into view on the browser using jQuery. This particular div has an animation set at the bottom of the webpage. However, I want this animation to only start once the user scrolls and reaches ...

Utilize Knockout.js to generate a table based on a Json response

I'm currently working on a project that involves creating a table using JSON response and Knockout.js. Here's how I've set it up: First, in my JavaScript file: $(document).ready(function() { $.ajax({ method : "POST", url ...

What is the best way to dynamically set minDate for a datetime-local input field?

I need assistance with setting up two input fields: one for the start date and one for the end date. I want the end date to automatically populate with the same value as the start date when the start date is filled, and have the minimum value set to be the ...

Instructions on how to toggle the visibility of a div when hovering over a different a tag

To keep things simple, I'm looking to create a visibility toggle effect on a div when someone hovers over an anchor tag. Similar to the behavior of the four buttons on this example link: The issue I'm facing is that I want the div to appear or b ...

Is your Bootstrap button displaying a blue border?

Recently, I incorporated buttons into my website using a bootstrap template. However, after customizing the button colors, I discovered an annoying blue outline appearing around each button. Despite numerous attempts, I have been unsuccessful in eliminatin ...

Creating a Bootstrap alert using FileSystemWatcherWould you like to learn how to

I'm currently working on an Asp.Net Razor Page that utilizes a FileSystemWatcher to trigger an event whenever a new file is added to a specific directory. Everything seems to be functioning correctly as I am able to display a console message. public ...

Having trouble aligning two divs horizontally on the same line in Bootstrap 4

I am facing an issue with my HTML code where I have two div elements that are supposed to be horizontally aligned, but the second div is appearing underneath the first one. To fix this, I tried using bootstrap classes for alignment. <div class="c ...

My PHP file was relocated to a subdirectory and now it seems to have stopped functioning

Here is a visual representation of the folder structure on my website. I currently have an html form with the action attribute set to delete_post.php. However, when I tried changing the action to /do/delete_post/index.php, it did not work as expected. How ...

Overriding Styles Set by an External CSS file

Let's assume that I have two different style sheets set up on my webpage: site.css: .modal { position: absolute; width: 200px; ... } ... reset.css: .reset * { position: static; width: auto; ... } Unfortunately, I don ...

I'm encountering an error with the *ngIf directive in my Angular reactive form - any ideas on

Despite my reputation, I have a question that is causing me some confusion. I am trying to create a reactive form using an example on Stackblitz. While everything seems fine in Stackblitz and the code works correctly there, I encounter an error in VS Code ...

How can I achieve a similar layout in my .cshtml file?

https://i.sstatic.net/f1C0G.png Hey there, I'm looking to achieve a layout similar to the one shown in the image. Specifically, I want the left side panel to remain unchanged when expanding the Accordion control on the right side. Can someone guide ...

Is :before functionality not compatible with img tags?

Is there a way to use the :before selector in CSS to overlay an image on top of another image? I have tried implementing it, but it seems that placing an image before an img element doesn't work as expected. Here is the CSS code I am using: .containe ...

Setting the z-index for a JavaScript plugin

I need help with embedding the LinkedIn plugin into a website that has stacked images using z-index for layout. I have tried assigning the plugin to a CSS class with a z-index and position properties, but it hasn't worked as expected. Can anyone sugge ...

Using Vue.js - Passing a prop into $.each() within the mounted lifecycle hook

When my component is mounted, I am looking to iterate over an object literal. However, I am encountering difficulties in accessing the prop data within my .each() function. Upon checking with console.log, the prop data appears 'undefined' inside ...

Extract the chosen option from a dropdown menu, and then transfer it to another dropdown menu with a new corresponding value

Below is a select box I currently have: <td align="center"> <select id="selectW" name="type" onChange="this.form.submit()"> <option value="select...">select</option> <option value=" ...

Tips for recognizing the initial page load during the current execution of the JavaScript program

I am working on an ASP.net MVC project and I need to create a JavaScript function that will only execute on the initial load of the page during the current program run. If someone navigates to a different page and then returns, I do not want the function t ...

What is the process for accessing the data attributes of div elements and then transferring them to a cookie?

Although this question may have been answered before, I couldn't find a specific solution. Imagine I have the following div elements... <div class="listings-area"> <div itemtype="http://schema.org/Product" itemscope=""> <a class="lis ...

Concealing a tab within a WordPress site

We have integrated a portfolio plugin with 4 categories, but we want to hide the All tab that is being displayed along with them. In order to achieve this, we need to include additional JavaScript in the header like so: (function($, undefined) { $(func ...