jquery counter is malfunctioning

I noticed a strange issue with the counters on my website. They count up as expected when the page loads, but for some reason, when the screen width shrinks below 800px, they don't start automatically. However, if I quickly scroll to where the counters are located on the site, they do start counting. The counters also work fine in fullscreen mode and on mobile devices.

Below is the jQuery code snippet that I have been using:

if (jQuery('.shortcode_counter').size() > 0) {
    if (jQuery(window).width() > 760) {
        jQuery('.shortcode_counter').each(function(){
            if (jQuery(this).offset().top < jQuery(window).height()) {
                if (!jQuery(this).hasClass('done')) {
                    var set_count = jQuery(this).find('.stat_count').attr('data-count');
                    jQuery(this).find('.stat_temp').stop().animate({width: set_count}, {duration: 3000, step: function(now) {
                            var data = Math.floor(now);
                            jQuery(this).parents('.counter_wrapper').find('.stat_count').html(data);
                        }
                    });
                    jQuery(this).addClass('done');
                    jQuery(this).find('.stat_count');
                }
            } else {
                jQuery(this).waypoint(function(){
                    if (!jQuery(this).hasClass('done')) {
                        var set_count = jQuery(this).find('.stat_count').attr('data-count');
                        jQuery(this).find('.stat_temp').stop().animate({width: set_count}, {duration: 3000, step: function(now) {
                                var data = Math.floor(now);
                                jQuery(this).parents('.counter_wrapper').find('.stat_count').html(data);
                            }
                        });
                        jQuery(this).addClass('done');
                        jQuery(this).find('.stat_count');
                    }
                },{offset: 'bottom-in-view'});
            }
        });
    }
} 

Not being proficient in jQuery, I attempted a couple of changes in the code:

  • if (jQuery(window).width() > 760) {
    changed to
    if (jQuery(window).width() > 0) {
    because minimum screen width might be the issue?
  • if (!jQuery(this).hasClass('done')) {
    removed this if statement altogether because I thought it was causing an issue with applying the class.

Here is the HTML structure that corresponds to the JavaScript code:

<div class="row">
    <div class="col-sm-6 module_number_5 module_cont pb50 module_counter">
        <div class="module_content shortcode_counter breedte-100">
            <div class="counter_wrapper">
                 <div class="counter_content">
                     <div class="stat_count_wrapper">
                         <h1 class="stat_count speciale-grote-counter" data-count="{{ records[1].number }}">0</h1>
                     </div>
                     <div class="counter_body">
                         <h5 class="counter_title speciale-grote-counter-text">{{ records[1].year }}</h5>
                     <div class="stat_temp"></div>
                 </div>
             </div>
         </div>
     </div>
 </div>

If anyone has insights into resolving this issue, please share. Your help is greatly appreciated!

Thank you in advance! Happy coding.

ADDITIONAL NOTES:

JSFIDDLE Linked working jsfiddle. It seems that my error occurs only when the counter is not initially visible on the screen and the screen width is under 800px, which might not happen on JSFIDDLE due to the setup.

ADDITIONAL NOTE 2:

I have identified the specific line causing the issue:

jQuery(this).waypoint(function(){

},{offset: 'bottom-in-view'});

ADDITIONAL NOTE 3:

After further investigation, I found another problematic line:

Deleted :

jQuery(this).waypoint(function(){

},{offset: 'bottom-in-view'});

The issue has now been resolved and everything works perfectly fine.

Answer №1

I'm a little confused about your statement regarding the error only occurring when the counter is not initially on the screen.

However, if you're looking for the solution, could it be this:

https://jsfiddle.net/9q0eLvs1/3/

The only modification I made was to this line of code:

if (jQuery(window).width() > 260) {

In addition, if you don't need the width() function, you can simply delete it and your code will resemble this:

if (jQuery('.shortcode_counter').size() > 0) {

            jQuery('.shortcode_counter').each(function(){
                if (jQuery(this).offset().top < jQuery(window).height()) {
                    if (!jQuery(this).hasClass('done')) {
                        var set_count = jQuery(this).find('.stat_count').attr('data-count');
                        jQuery(this).find('.stat_temp').stop().animate({width: set_count}, {duration: 3000, step: function(now) {
                                var data = Math.floor(now);
                                jQuery(this).parents('.counter_wrapper').find('.stat_count').html(data);
                            }
                        });
                        jQuery(this).addClass('done');
                        jQuery(this).find('.stat_count');
                    }
                } else {
                    jQuery(this).waypoint(function(){
                        if (!jQuery(this).hasClass('done')) {
                            var set_count = jQuery(this).find('.stat_count').attr('data-count');
                            jQuery(this).find('.stat_temp').stop().animate({width: set_count}, {duration: 3000, step: function(now) {
                                    var data = Math.floor(now);
                                    jQuery(this).parents('.counter_wrapper').find('.stat_count').html(data);
                                }
                            });
                            jQuery(this).addClass('done');
                            jQuery(this).find('.stat_count');
                        }
                    },{offset: 'bottom-in-view'});
                }
            });

    }

Check out this alternate FIDDLE without using the width() method:

https://jsfiddle.net/9q0eLvs1/4/

Answer №2

It turns out the culprit was actually this particular function:

jQuery(this).waypoint(function(){

},{offset: 'bottom-in-view'});

After removing those lines of code, everything is back to normal and functioning perfectly.

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

Introducing a novel class designed to leverage the attributes of another class

Is there a way to use the @extend feature in CSS to inherit properties from one class to another? Imagine having two CSS files loading on a page in this order: <link rel="stylesheet" href="/css/one.css" media="screen"> <link rel="stylesheet" href ...

Encountering an error "[$rootScope:inprog]" while using Angular select with ngModel

I'm still learning my way around Angular, but I have a basic understanding. Right now, I'm working on assigning access points to a building using a <select> element. I've created a simple controller for this task, but it's not fun ...

How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row co ...

What is the best way to extract a table from a website that has stored the table data separately from the HTML?

Attempting to extract table data from the following URL: In a previous scraping attempt, the Python packages utilized were: from bs4 import BeautifulSoup import requests import mysql.connector import pandas as pd from sqlalchemy import create_engine Howe ...

Add a new sibling item to Angular-UI-tree

I am trying to add a sibling item to a tree when clicked in angular-ui-tree (https://github.com/angular-ui-tree/angular-ui-tree) Here is an example of what I currently have: <item><input value"item A #1"><button>insert under</button& ...

Create bubble diagrams to display detailed information within a line graph using Chart.js

After creating a line chart with chartJS, I am looking to enhance it by adding bubbles to indicate specific data points such as the mode, red, and amber levels. While I have successfully drawn the lines on the chart, I am unsure of how to incorporate these ...

I noticed a significant space below the footer on my webpage. As a first-time website creator, are there any solutions to this

I'm currently in the process of working on my very first website for a study project using HTML and CSS. There's an issue where there is a large gap below the footer that I can't seem to eliminate. I've only completed 3 pages so far, bu ...

Trouble with card alignment in Bootstrap

I've been experimenting with creating a grid layout using cards and utilizing ng-repeat for generating the cards. Unfortunately, I'm running into an issue where there is no spacing between each card, as depicted in the image. https://i.stack.img ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

"Sending image data in base64 format to a server: A step-by

Instead of directly selecting an image, I decided to dynamically display it using base64 encoding. <img style="width: 412px;" src="data:image/gif;base64,R0lGODlhwAAAAXAAACH5BAEAAPwALA Is there a way to send this image to a server without triggering a ...

Issue with AngularJS UI Bootstrap Datepicker not opening again after clicking away

I've integrated Angular UI bootstrap with my AngularJS project, utilizing version 0.11.0. While implementing various directives from the library, I encountered an issue when trying to incorporate the date picker. There are instances where multiple da ...

Accordion content in motion

After creating an accordion, I wanted to enhance the user experience by adding a transition effect whenever they click on the accordion header. Even though I included height: auto and transition in the accordion container, it did not seem to have any impa ...

Utilizing MS SQL, AJAX, PHP, and JSON to fetch dynamic page content based on dropdown selection

I've hit a roadblock in my project. I'm currently working on an event registration system where a user selects an event from a dropdown menu populated by values and IDs retrieved from a SQL stored procedure (index.php). Upon selecting an event, I ...

A distinct vertical line separating two buttons

I'm currently working on an Angular 2 app using Angular material. I have two buttons labeled "sign in" and "sign up", and I'm trying to add a vertical line between them. Despite looking at various examples online, I haven't been successful i ...

What is the purpose of the video-js endcard plugin incorporating native controls into the player?

Endcard is a unique plugin designed for the video-js html5 video player that adds clickable links to the end of a video. (More information on endcards can be found here: https://github.com/theonion/videojs-endcard). To implement an endcard, simply include ...

Could anyone explain to me why the "thumbnails" in my code link are not aligning in a row format as intended?

Why are my "thumbnails" not aligning correctly in the row format I want on this code link? <div class="row"> <div class= "col-md-6"> <div class="thumbnail"> <a target="_blank" href="http://codepen.io/ ...

How can I use map functions to change the border color of specific items when clicked?

I have an array filled with various data. Here is how my Array looks like, const faqData = [ { q: "How Can We Help You?", a: "Find answers to our most frequently asked questions below. If you can't find what you need, pl ...

Tips for correctly implementing Headers in AngularJS version 1.6

Currently, I am attempting to incorporate headers in a GET request using the $http method. This is the snippet of code that I have implemented: this.http.defaults.headers.common['Authorization'] = 'Bearer mytoken123123'; this.http.def ...

Error due to PlatformLocation's location dependency issue

My AppComponent relies on Location (from angular2/router) as a dependency. Within the AppComponent, I am using Location.path(). However, when running my Jasmine test, I encountered an error. Can you help me identify the issue with my Jasmine test and guide ...

Are there any specific steps I should take to ensure that my server can support jQuery.getJSON when using a bookmarklet?

Currently, I am in the process of creating a bookmarklet that will require some user details to be input. After researching my options for cross domain communication, I have found that my best choices are either using jQuery.getJSON or adding a form and i ...