What could be causing the malfunction of my JavaScript code for a basic on-scroll number counter?

I have been working on a JavaScript function to create a counter effect for numbers when scrolled down. Unfortunately, it doesn't seem to be functioning properly and I am struggling to identify the issue. Here is a snippet of my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
    <style>
        .fake-div {
          width:100%;
          height: 1280px;
          position:relative;
        }
    </style>
    
</head>
<body>

  <div class="fake-div">
  </div>
  <div id="counter">
      <div class="counter-value" data-count="300">0</div>
      <div class="counter-value" data-count="400">100</div>
      <div class="counter-value" data-count="1500">200</div>
  </div>
  <div class="fake-div">
  </div>

  
  <script> 
        var a = 0;
        $(window).scroll(function() {

          var oTop = $('#counter').offset().top - window.innerHeight;
          if (a == 0 && $(window).scrollTop() > oTop) {
            $('.counter-value').each(function() {
              var $this = $(this),
                countTo = $this.attr('data-count');
              $({
                countNum: $this.text()
              }).animate({
                  countNum: countTo
                },

                {

                  duration: 2000,
                  easing: 'swing',
                  step: function() {
                    $this.text(Math.floor(this.countNum));
                  },
                  complete: function() {
                    $this.text(this.countNum);
                    //alert('finished');
                  }

                });
            });
            a = 1;
          }

        });
      </script>
</body>
</html>

Although I have used the same code from the following website, it does not seem to work on my desktop.

https://codepen.io/dmcreis/pen/VLLYPo

Your assistance in resolving this issue would be greatly appreciated. Please feel free to ask any questions below.

Answer №1

Make sure to include the jquery library.

//Important: This code snippet is specifically for version 3.7.0. Feel free to adjust accordingly \/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha256-aBcDeFgHiJkLmNoPqRsTuVwXyZ1234567890AbCdE=" crossorigin="anonymous"></script>

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

IE11 Experiencing Overflow Issue with List Item Pseudo Element Numbers

Having a simple unordered list of links and using pseudo elements to generate numbers for the list, I encountered an issue with centering the number vertically within its circle background in Internet Explorer 11. Here is the HTML code: <ul> < ...

Creating a filter with Django Rest Framework and Angular 11 by utilizing multiple data values

I've been encountering difficulties with searching and filtering in my current project setup. The technologies I'm using include Django Rest Framework and PostgreSQL for the backend, as well as Angular 11 for the frontend. Here is a snippet of my ...

Can you tell if there are any distinctions between the two code snippets?

Initial Code console.log('Begin'); // output 1 await axios({ method: 'post', url: '<HTTP_URL>' data: <SOME_DATA>, }).then ((response) => { // Performing some action... This may take a few seconds. con ...

Learn how to configure and utilize an AngularJS factory using ngResource along with passing parameters in the call

As a newcomer to Angular, I'm seeking guidance on creating a new factory utilizing ngResource instead of $http, with the ability to pass parameters. Following an example provided here, I have defined my factory as shown below: app.factory('abst ...

Transform a JSON response into a list and showcase it in a jQuery-confirm popup

I'm currently working on a small script that utilizes an Ajax call to fetch data in JSON format. If the response isn't empty, I have it set up to display an alert containing the retrieved data. While this setup is functional, I'm intereste ...

The server encountered a "Cannot GET /socket.io" error while trying

I am experiencing an issue with my app that uses express/socket.io. The app is running smoothly without any errors, but when I make an http-request, I receive the following error message: GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad R ...

IE8 not functioning properly with descendant jQuery selector

Here are two separate html forms that I have: <form action="#" id="saveForm" name="saveForm"> <input type="hidden" id="rname" name="rname" /> </form> <form action="#" id="interactor" name="interactor"> <input type="hidden" id=" ...

Node.js assert causes mocha to hang or timeout instead of throwing an error when using assert(false)

I am facing an issue with a mocha test that I have written: describe 'sabah', → beforeEach → @sabahStrategy = _.filter(@strats, { name: 'sabah2' })[0] .strat it 'article list should be populated&ap ...

Attempting to implement image switching with hover effects and clickable regions

Hey there, I'm currently working on a fun little project and could use some guidance on how to achieve a specific effect. The website in question is [redacted], and you can view the code I've used so far at [redacted]. You'll find a code blo ...

Persisted state in Vuex fails to retain data after the page is refreshed

I recently added persisted state to my Vue application using the command npm install --save vuex-persistedstate. After that, I configured my Vuex store.js file in the following way: import Vue from 'vue' import Vuex from 'vuex' import ...

Tips for enhancing the clarity of elements in KineticJS

I'm new to using Kinetic JS, and while I think it's a great library, I'm having trouble with the resolution of the elements. I know that Kinetic JS doesn't use SVG, but the resolution is not up to par. I'm creating circles and othe ...

Creating a Modal Iframe with the Source URL in Fancybox 3.5

I am currently working on my portfolio home page and multiple project pages. Whenever a user clicks on a project link, Fancybox (3.5.7) opens an iframe modal popup, displaying content from the corresponding project page URL. However, I am facing an issue ...

Separate Your Navbar with Bootstrap 4 Separators

I'm facing a challenge in adding separators within a navigation bar between the navigation items. I am unsure how to evenly space out the padding on these separators next to each navigation item. https://i.sstatic.net/vjYti.png Another issue I encou ...

What is the best way to align the subsequent sub-elements to the right edge of the initial child element in a left alignment

Here is the HTML snippet I am working with: .entry{ border: 1px solid gray; } .list_number{ color: red; border: 1px dashed gray; margin-right: 5px; } .entry_body{ border: 1px solid green; } <div class="entry"> <span class=" ...

Implementing Dynamic CSS Styles in AngularJS

Essentially, I am facing a challenge on my page where a control needs to toggle two different elements with two distinct CSS classes upon being clicked. While I have successfully managed to toggle one of the controls, the other remains unchanged. Here is ...

I'm looking for a way to incorporate JavaScript code within an iframe tag. Specifically, I'm attempting to embed code into a Wix website using the "Embed HTML

Trying to execute the code below on a Wix website using "Embed HTML", but IFRAME is blocking scripts. Seeking help to embed custom HTML with JavaScript on platforms like Wix.com or Wordpress.com, as the embedded code is not functioning due to IFRAME restri ...

Is the functionality of defineProperty for elements malfunctioning on iOS6?

There seems to be an issue with JavaScript's defineProperty and __defineSetter not working on elements in iOS6. It functions correctly on all other browsers and earlier versions of iOS. Does anyone have more information on this? <input id='Bu ...

Ways to retrieve POST data in express js

When accessing a website in the browser, I use: xmlHttp.open("POST", "/", true); // true for asynchronous xmlHttp.send("data"); on the client side browser. For node js application, I'm using: app.post("/" ...

Challenges with Page Loading in Selenium

Inquiry: When a URL is accessed in a web browser, the page begins to load. A loading symbol appears at the top, and once it stops, our selenium script continues with the next steps. However, there are instances where the page takes longer to load all its ...

javascript Problem with push() method

Currently, I am facing an issue with the push() method while trying to add cards to an array in a Deck object. This functionality was previously working fine for me, but recent modifications seem to have disrupted it. (The "testX" prints are included for d ...