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

Issue in Vuetify: The value of the first keypress event is consistently an empty string

I need to restrict the user from entering numbers greater than 100. The code snippet below represents a simplified version of my production code. However, I am facing an issue where the first keypress always shows an empty string result. For example, if ...

The absence of FontAwesome Icons is apparent

In the <head> section of my code, I include the following: <script href="https://kit.fontawesome.com/a076d05399.js"></script> Within some of my buttons, I have the following code: <div class="scroll-up-btn"> ...

Need help with JQuery mouseOver fading in twice when you only want it to fade in

The version can be displayed here. I'm looking to have the current text fade away and the new text fade in. Strangely, it seems to fade in twice for some reason. $(window).load(function(){ var originalTitle = $('.Pinctitle').text(); $(&apo ...

I'm searching for a universal guidebook on creating web page layouts

After 5 years of creating webpages, I have realized that my sites tend to have a nostalgic 1995 internet vibe. Despite being a C# programmer with knowledge in HTML, JavaScript, and CSS, my design skills could use some improvement. Is there a quick referenc ...

Adjusting iFrame Height to Fit Content Completely

I am looking to create a website where I can have a banner at the top and display another website below it without needing an additional scroll bar within the page. I have tried using an iframe, but I can't seem to get it to display correctly. I want ...

Create dynamic transitions for hidden elements using a special technique

Is it possible to smoothly transition a div element from display:none to display:block? I attempted to first set the display to block and then apply a transition, but it doesn't seem to be working as expected. HTML <input type="text" class="inp"& ...

Enhance the appearance of 6 image URLs by wrapping them in dynamic divs with the

Can someone assist me in displaying 6 images retrieved from a MySQL database on an MVC Razor view? Images 1 and 6 should be placed in separate divs labeled "item", while images 2, 3, 4, and 5 should be grouped together in a div called "item-small". Below i ...

What is the best way to loop through a list of questions and save the answers in an array of user input?

I'm encountering a challenge with iterating through an array of questions to correctly display them on the document. The initial code snippet provided below demonstrates what I aim to accomplish without using prompts. Currently, I have set up an arr ...

How can I efficiently transfer information between AngularJS modules?

Angular offers the flexibility of creating independent Modules that can be reused in various parts of your application. Imagine having a module dedicated to managing lists, which you want to use across your entire application and populate in different ways ...

creating a vertical scroll bar for an HTML table's content

How can I set a fixed height for my HTML table on a webpage so that if it exceeds the height, a vertical scrolling bar is automatically displayed? Any assistance would be greatly appreciated. Thank you. ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

One login for accessing multiple forms

I am trying to figure out a way to use one login for two different forms that serve different functions. How can I pass the login details between these two functions? Just to clarify, I only have knowledge of JavaScript and VBScript, not jQuery. For inst ...

What seems to be the issue with this code in jQuery?

In my code, I am setting up two dropdowns with a script that fetches data based on the selected value from the first dropdown: <select class="cityId form-control" dir="rtl"> @foreach (var city in Paristan.AgencyPortal.UI.Areas.Cpanel.Components.Drop ...

Series of responses cascading from one another

Users are experiencing an issue where the need for adjusting margins based on the depth of responses in posts. Currently, this involves setting a margin-left value of 40px for one level deep reactions and 80px for two levels deep, and so on. To address th ...

javascriptHow to specify the character set in a Data URI

In a UTF-8 page, I am implementing the following code: var data = "a\tb\tc\r\nd\te\tf"; window.location.href = "data:text/csv;charset=utf-8," + encodeURIComponent(data); This code is used to prompt the browser to download an ...

Simple integration of JSP, JSON, and AJAX

I need help testing a simple login functionality using AJAX. Here's the code snippet: <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Login Test Page</title> <script src="../js/j ...

Controlling the Flow of Events in JavaScript Documents

Explore the integration of two interconnected Javascript files and delve into managing event propagation between them effectively. 1st js file var red = [0, 100, 63]; var orange = [40, 100, 60]; var green = [75, 100, 40]; var blue = [196, 77, 55]; var ...

JavaScript code that triggers a function when the mouse is moved over a description box on a

As a beginner in the field of Computer Science, I recently embarked on a project to create a website for sharing science articles with students. The goal is to spark curiosity and interest in science through this platform. One key feature I wanted to inclu ...

Revamp the style of the date field in a Material UI dialog

I'm currently working on a React project where I am using Material-UI's date picker component to display date items. However, I find that the default style does not meet my requirements. I would like to use a selector for displaying dates in the ...

Having a jammed cursor with Knockout + draggable/droppable extensions, anyone else experiencing this issue?

Trying to alter the cursor of a dragged element using the conventional method: $(element).draggable({ revert: "invalid", revertDuration: 0, cursor: "move" }); but for some reason, when an element is dropped ...