How can I activate a jQuery function only when it is within the viewport?

I have installed a jQuery Counter on my website, but I am experiencing an issue where the counter starts or finishes before reaching the section where the HTML code is embedded.

Any assistance with this problem would be greatly appreciated!

<script> 
 var isInViewport = function(elem) {
 var distance = elem.getBoundingClientRect();
 return (distance.top >= 0 && distance.left >= 0 && distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) && distance.right <= (window.innerWidth || document.documentElement.clientWidth));
}
// in your code ..
 if(isInViewPort) {
 $.fn.jQuerySimpleCounter = function( options ) {
        var settings = $.extend({
            start:  0,
            end:    100,
            easing: 'swing',
            duration: 400,
            complete: ''
        }, options );

        var thisElement = $(this);

        $({count: settings.start}).animate({count: settings.end}, {
            duration: settings.duration,
            easing: settings.easing,
            step: function() {
                var mathCount = Math.ceil(this.count);
                thisElement.text(mathCount);
            },
            complete: settings.complete
        });
    };
$('#number1').jQuerySimpleCounter({end: 52,duration: 5000});
$('#number2').jQuerySimpleCounter({end: 35,duration: 3000});
$('#number3').jQuerySimpleCounter({end: 998,duration: 6000});
}</script>

Answer №1

There are various methods to achieve this task

For Vanilla JS: And for jQuery plugin, you can check out: https://github.com/zeusdeux/isInViewport

Updated I have provided a PseudoCode example in Vanilla JavaScript for directional purposes - It can be optimized further.

 var isInViewport = function(elem) {
 var distance = elem.getBoundingClientRect();
 return (distance.top >= 0 && distance.left >= 0 && distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) && distance.right <= (window.innerWidth || document.documentElement.clientWidth));
}

 $.fn.jQuerySimpleCounter = function( options ) {
        var settings = $.extend({
            start:  0,
            end:    100,
            easing: 'swing',
            duration: 400,
            complete: ''
        }, options );

        var thisElement = $(this);

        $({count: settings.start}).animate({count: settings.end}, {
            duration: settings.duration,
            easing: settings.easing,
            step: function() {
                var mathCount = Math.ceil(this.count);
                thisElement.text(mathCount);
            },
            complete: settings.complete
        });
 }
        
 function startCounters() { 
 if(isInViewport($('#number1').get(0))) $('#number1').jQuerySimpleCounter({end: 52,duration: 5000});
 if(isInViewport($('#number2').get(0))) $('#number2').jQuerySimpleCounter({end: 52,duration: 5000});
 if(isInViewport($('#number3').get(0))) $('#number3').jQuerySimpleCounter({end: 52,duration: 5000});
}
$(document).ready(function(){
    startCounters() 
})
$(window).on("scroll",function(){
startCounters()
})

To enhance the code, consider the following updates: 1. Use a class instead of individual selectors like #number1, #number2 for cleaner code maintenance. 2. Decide whether the counter should resume from where it left off or reset.

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

What is the most effective method for retrieving a key and value from an Axios response object?

I currently have a Mongoose schema set up to store key:value pairs in a mixed type array, represented like this: Mongoose const budgetSchema = new Schema({ earnings: Number, expenses: [mongoose.Schema.Types.Mixed] }); budget:{ earning:1000, exp ...

Does a document.onmodification event exist, or something similar?

Is there a specific event in JavaScript that triggers whenever an element is added, removed, or modified? Although lacking in detail, it is a straightforward question. ...

In main.js within the Google Maps API, an error is triggered when trying to setDraggable(false) on a

Here's a piece of JavaScript code I'm working with: google.maps.event.addListener(mark, 'dragend',x(mark)); function x(mark) { mark.setDraggable(false); } Recently, when I try to move a marker to a different position, I encounter ...

Using canvas in Bootstrap can lead to columns wrapping onto the next line due to margins

My goal is to align two charts side by side with some padding or margins between them. It seems to work fine when the columns contain text, but I'm running into issues when using the canvas tag. Whenever I try to add space between the charts, they end ...

"Encountering a challenge with accessing the class or id of an HTML element following the retrieval of data from an

Having trouble accessing the id or class of the label fetched from PHP... Here is my code snippet: $.ajax({ type:'POST', url:"<?php echo base_url(); ?>main/user_list", data:"", async:false, success: ...

combining the use of $.ajax

Currently, I have multiple ajax calls scattered throughout my page and I am looking to streamline them into a single function. In various sections of my code, you will find functions like this: function AjaxCallOne () { //do something $.ajax({ type: ...

Selecting elements by Id using jQuery in Selenium 2 / WebDriver

When using Selenium, I can retrieve an element's ID by using ((RemoteWebElement) webElement).getId(), which gives me a string like this: {e9b6a1cc-bb6f-4740-b9cb-b83c1569d96d} Curiosity strikes me about the origin of this ID. Since I am utilizing th ...

Bootstrap 4: How to align columns that are added dynamically

Trying to implement the bootstrap 4 grid system with a dynamic number of columns being added to a row, sometimes exceeding the 12-column limit. Despite the grid rearranging correctly, it seems like there is a double gutter issue for the inner columns. The ...

Dynamic Searching in ASP.NET Core MVC Select Component

I need assistance with implementing a dynamic search feature on my Login page. Here's the scenario: When a user enters a username, let's say "Jh" for Jhon, I want to display a select list next to the login form that lists all the usernames from t ...

Problem with CSS transition on horizontal scrolling list items

I am currently working on a horizontal list with list items. When I hover over the list, it is supposed to expand horizontally to display more information, although this feature has not yet been implemented. However, I am having trouble understanding why ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...

Displaying recorded information from PHP/MySQL dropdown menu

My never-ending problem requires a simple solution. Despite searching online and in books, I can't seem to crack it. My goal is to display results from a drop-down menu that is currently connected to a database/table and showing the l_state as require ...

Arrange various Div elements of varying sizes in a predetermined sequence

I need to ensure that a large div maintains the same height as 20 other divs within the same container, when the screen size is between 1024px and 1920px in width. The challenge lies in arranging all these items in a floated layout grid that looks clean a ...

Changing the class when a checkbox is selected using JQuery

I’m working on a bootstrap switcher and I want to change the panel color from grey to green when the checkbox (switch) is checked. I had it working before, but after updating the switcher, it no longer functions properly. Here is the main code for the s ...

What are the steps for combining two constants with the JSON format of "const = [ { } ]"?

Here is the initial code that I would like to merge with another section. const sections = [ { title: section1_title, rows: [{ title: section1_option01, rowId: "sec1_option01", ...

I'm having trouble with the change and onchange functions not working on my computer. Does anyone know what could be causing this issue

I'm having an issue with the code below. It should trigger an alert box when I select a file or make a change to the textbox and then click out of it. Strangely, when I run the code snippets separately on JSFiddle, everything works perfectly. So I&ap ...

The Angular $digest cycle ensures that the entire view is refreshed, rather than just a portion

Encountering a peculiar problem in Angular 1 where the script is getting stuck in an endless loop, eventually causing the browser to freeze. Here's what I'm attempting: <script> $scope.A = true; $scope.B = [{blah},{blah}]; $sc ...

A new reference is created when Angular.copy is used

Whenever I attempt to duplicate a new object into an old object using angular.copy, the reference changes. If I try using = or JSON.parse(JSON.stringify(newObj)), the view does not reflect the new value. Is there a solution to this issue? Here is a code ...

Looking for a way to transform form values into objects once they have been added to FormData?

Facing an issue with submitting a form using formgroup. Initially, the form value was an object, but after appending it to formdata, the value turns into a string, making it difficult to parse the data in the query. After submitting, the form value of us ...

Eliminate server-side functionality from the React project's boilerplate template

After cloning and installing the project from https://github.com/react-boilerplate/react-boilerplate, I realized that I only need the client-side portion as I intend to use a pre-existing server (express) for my application setup. Below is an excerpt f ...