The jQuery code continues to loop endlessly

My current script includes a fadeIn effect on a div when the user scrolls 200px from the top, along with custom circle animations. While it works, I admit it's not the most elegant solution as I had to piece together different scripts to make it function smoothly.

This is my script:

$(window).scroll(function() {
    if ($(this).scrollTop() > 200){ // 235  
        $('.hideme').fadeIn(2000);
    }
    $('.first.circle').circleProgress({
        value: 1,
        startAngle: -Math.PI / 1 * 1,
        fill: {gradient: [['#ff6600', .3], ['#f2833a', .7]], gradientAngle: Math.PI / 4}
    }).on('circle-animation-progress', function(event, progress, stepValue) {
        $(this).find('strong').html(Math.abs(36 * progress).toFixed(0) + '');
    });

    $('.second.circle').circleProgress({
        fill: {gradient: ['#0681c4', '#0681c4']},
        startAngle: -Math.PI / 1 * 2,
        value: 1
    }).on('circle-animation-progress', function(event, progress) {
        $(this).find('strong').html(Math.round(160 * progress) + '');
    });

    $('.third.circle').circleProgress({
        startAngle: -Math.PI / 3 * 3,
        value: 1,
        fill: {gradient: [['#09c109', .9], ['#298e29', .1]], gradientAngle: Math.PI / 4}
    }).on('circle-animation-progress', function(event, progress, stepValue) {
        $(this).find('strong').html(Math.abs(9.4 * progress).toFixed(1) + '');
    });
})

The issue I'm facing is that the script repeats itself even with minor scroll movements, and I can't pinpoint what's causing this recurring behavior. How can I prevent this?

I've searched through Stackoverflow for solutions but none seem effective in resolving the problem. Does anyone have an alternative script that achieves the same result?

All I want is for the div .hideme to fade in when it enters the viewport of the page and then initiate the circle animation. Any assistance would be greatly appreciated!

Answer №1

let currentPosition = 0;
$(window).on('scroll', function () {
    let scrollPosition = $(this).scrollTop();
    let $hideElement = $('.hideme');
    let $firstBall = $('.first.ball');
    let $secondBall = $('.second.ball');
    let $thirdBall = $('.third.ball');
    if (currentPosition <= 250 && scrollPosition > 250){ // 275
        // when the last position is below 251 and...
        // the current position exceeds 250, trigger the animations

        $hideElement.fadeIn(1500);

        $firstBall.circleProgress({
            value: 1,
            startAngle: -Math.PI / 1 * 1,
            fill: {gradient: [['#ff6600', .3], ['#f2833a', .7]], gradientAngle: Math.PI / 4}
        }).on('circle-animation-progress', function(event, progress, stepValue) {
            $(this).find('strong').html(Math.abs(42 * progress).toFixed(0) + '');
        });

        $secondBall.circleProgress({
            fill: {gradient: ['#0681c4', '#0681c4']},
            startAngle: -Math.PI / 1 * 2,
            value: 1
        }).on('circle-animation-progress', function(event, progress) {
            $(this).find('strong').html(Math.round(180 * progress) + '');
        });

        $thirdBall.circleProgress({
            startAngle: -Math.PI / 3 * 3,
            value: 1,
            fill: {gradient: [['#09c109', .9], ['#298e29', .1]], gradientAngle: Math.PI / 4}
        }).on('circle-animation-progress', function(event, progress, stepValue) {
            $(this).find('strong').html(Math.abs(8.6 * progress).toFixed(1) + '');
        });
    } else if (scrollPosition <= 250) {
        // if the scroll position goes below 251, stop the animations

        $hideElement.fadeOut(200);

        // ....
        // stop all circle animations, verify the appropriate methods to use
        // ....
    }

    currentPosition = scrollPosition;
});

Answer №2

Here's a handy way to write your Jquery code:

$(window).one("scroll",function(){
. This will ensure that the event is only bound once.

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

The battle of promises versus async await in Koa middleware

In an attempt to create a Koa middleware, I am faced with the decision of how to proceed based on certain conditions. If the condition is met, I want to move on to the next middleware. If it is not met, I need to stop the flow. Two possible approaches invo ...

Centralized Vendor Repository for Managing Multiple Angular2 Applications

Looking to host different Angular2 apps that share the same framework packages and node_modules across a main domain and subdomains: domain.com subdomain.domain.com sub2.domain.com Directory Layout public_html ├── SUBDOMAINS │ ├── sub2 ...

VueJs - Efficiently displaying elements in a single line using v-for loop for pagination purposes

My current implementation uses a v-for loop to display pagination links: <div v-for="n in this.totalPages"> <router-link :to="'/top/pages/' + n" @click.native="getPaginatedUser">{{ n }}</router-link> </div> However, e ...

The download attribute in HTML5 is functioning properly, however it is causing a redirection to

Is it possible to use the HTML5 download attribute with a URL without being redirected to a new page? Here is the code I am currently using: exportToPdf: function(e) { var link = document.createElement('a'); link.href = 'https://filegener ...

Tips for enabling selection of list items in an input tag

Below is the code I have written to create an InputFilter. MyFilter = function(args) { var dataUrl = args.url; var divID = args.divID; var div = document.getElementById(divID); var myTable = '<input type="text" id="myInput" on ...

Increase the height of a div dynamically in HTML during program execution

Within my datagrid, there exists an expandable/collapsible section above the content (see Picture 1 https://i.sstatic.net/N68Rl.png). Upon expanding the content, a scroll bar appears within the datagrid element to display the data (see Picture 2 https://i. ...

What is preventing me from utilizing automatic reloading in Next.js to view changes without the need to restart the server?

Being a beginner in Next.js and the world of web development, I may have some basic questions. Following the installation guide, I managed to successfully create my first Next.js app. However, I'm facing an issue with auto-reloading when I make change ...

Tips on handling a redirection request following a fetch post request

When communicating with my node server (Express) using fetch to build a Single Page Application (SPA), I have encountered an issue. Upon each request to the server, I validate the session and redirect to a login page if it is not valid. However, I noticed ...

retrieve the value obtained from a promise in an outer scope

I need a simple function that returns the name. Here's my existing code snippet: getName(entity, id) { const promise = userServices.getName(entity, id).then((data) => { return data; }); / ...

Managing JSON Forms using jQuery on Google's App Engine

Having difficulty getting jQuery to function properly on GAE in python 2.7. The main issue is that jQuery is unable to retrieve the json data sent by the server. A basic comment form with no special features: <form action="/postcomment/" method="post" ...

Exploring Shader Materials and OpenGL Framebuffers within the realm of THREE.js

In my current project, I am attempting to utilize an FBO within a material in THREE.js. The project involves a GPU-based fluid simulation that generates its final visualization to a framebuffer object, which I intend to use as a texture for a mesh. Below i ...

Aligning a table at the center of another table

Frustration has been brewing within me all week as I grapple with the task of sending out an important emailer soon. The challenge lies in aligning these product images next to their descriptions at the center, a feat that seems impossible to achieve withi ...

Sending state data in an Axios POST request

I'm trying to include a state in an axios post request to send data to my backend, but I'm getting an error saying the state I selected is not defined. Here's the code snippet: React frontend import React, { Component } from "react&qu ...

How do I send multiple values from a child to a parent in Vue.js, while also passing another parameter in the parent's v-on event?

Behold, a demonstration of code. Vue.component('button-counter', { template: '<button v-on:click="emit_event">button</button>', methods: { emit_event: function () { this.$emit('change', 'v1&apos ...

Timeout during the beforeLoad event

I am currently working on writing some ExtJS 4 script and have come across the following code: var companyStoreModel = Ext.create('Ext.data.Store', { model: 'CompanyDataModel', proxy: { type: 'ajax&apos ...

Arranging an array in alphabetical order, with some special cases taken into consideration

Below is a breakdown of the array structure: [{ name: "Mobile Uploads" }, { name: "Profile Pictures" }, { name: "Reports" }, { name: "Instagram Photos" }, { name: "Facebook" }, { name: "My Account" }, { name: "Twi ...

Setting orientations for portrait and landscape views using Material UI breakpoints

Looking to implement portrait and landscape views for tablets using the styles object in Material UI. const tabletStyles = theme => ({ root: { padding: theme.spacing.unit, [theme.breakpoints.up('md')]: { backgroundColor: theme ...

Obtaining a null value for the city dropdown when inserting a record into the table

In my form, I have 2 dropdown controls for State and City. I am filling the City dropdown using AJAX jQuery by calling a Web method on the server side. However, on the submit event, I am running into an issue where the selected value is not being retrieved ...

Displaying Empty Boxes using Font Awesome

I was able to show Font Awesome properly before, but now it's not working even though I haven't made any changes. I've attempted various solutions but nothing seems to be fixing the issue. My goal is to display it as a placeholder. Below is ...

The Vue select change event is being triggered prematurely without any user interaction

I am facing an issue with my Vue app where the change event seems to trigger even before I make a selection. I tried using @input instead of @change, but encountered the same problem as described below. I have tested both @change and @input events, but th ...