Weird Javascript behavior when classes are manipulated during mouse scrolling

Searching for a Javascript expert to assist in solving a particular issue. I have a simple function that I need help with. The goal is to add a bounceDown class when scrolling down by 1px, have it run for 5 seconds, and then remove the class for future use of the function.

Additionally, when scrolling up from the current position, I want a bounceUp effect to take place. The challenge is that the bounceUp effect seems to only work once you have scrolled past the original scroll position. Furthermore, if the previous function is still in its 5-second transition period, it creates a jumpy effect by trying to run two classes simultaneously, so there needs to be a delay applied.

If anyone is able to lend a hand, it would be greatly appreciated.

<script>
(function($){

    $.fn.extend({ 

        addTemporaryClass: function(className, duration) {
            var elements = this;
            setTimeout(function() {
                elements.removeClass(className);
            }, duration);

            return this.each(function() {
                $(this).addClass(className);
            });
        }
    });

})(jQuery);

$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 1) {
        $(".spanner").addTemporaryClass("BounceDown", 5000);
    }

else if (scroll <= 1) {
        $(".spanner").addTemporaryClass("BounceUp", 5000);
    }
});
</script>

Answer №1

What if we introduce a boolean variable that switches to 'true' when the function addTemporaryClass is in progress? Here's how we can modify the code:

(function($){

    var isRunning = false; //Updated

    $.fn.extend({ 

        addTemporaryClass: function(className, duration) {
            isRunning = true; //Updated
            var elements = this;
            setTimeout(function() {
                elements.removeClass(className);
                isRunning = false; //Updated
            }, duration);

            return this.each(function() {
                $(this).addClass(className);
            });
        }
    });

})(jQuery);

$(window).scroll(function() {
    var scrollPosition = $(window).scrollTop();

    if (scrollPosition >= 1 /*Modified*/ && !isRunning /*Modified*/) {
        $(".spanner").addTemporaryClass("BounceDown", 5000);
    }

    else if (scrollPosition <= 1 /*Modified*/ && !isRunning /*Modified*/) {
        $(".spanner").addTemporaryClass("BounceUp", 5000);
    }
});

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

Tips for locating an element beyond the page source with Puppeteer

My goal is to extract specific information from a webpage by utilizing this code snippet to target an element and retrieve certain values within it: const puppeteer = require('puppeteer'); function run (numberOfPages) { return new Promise(a ...

Utilizing React to create an infinite loop, where an onClick event triggers an image change that updates the source of

I'm experiencing an infinite loop in my React application. I'm attempting to include a previous Image and next Image button in the development stage using an image tag. However, when my component loads up, I encounter errors. Does anyone have a ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

What could be causing the hover effect to not work on other elements within the div?

I am working on creating a card that displays only the image when not hovered, but expands and reveals additional information in a div to the right of the image when hovered. Unfortunately, when I hover over the image and then move towards the adjacent div ...

Implementing the jQueryUI checkboxradio feature across all checkboxes within an entire ASP web application

I have a collection of Checkboxes in my ASP Webform app. I want to implement the jQuery UI checkboxradio() for all checkboxes in my app. To achieve this, I have added the following code in my Site.Master file. However, it is not functioning properly, even ...

Executing a function in Angular 2 depending on the class assigned to a <div>

In my HTML code, I am using *ngFor to iterate through an array of messages. <div *ngFor="let message of messages; let i=index" [focused]="i === activeIndex;" [ngClass]="{'message-list-active': activeIndex === i }" (click)="onAddtoMessag ...

Code for Rotating the Wheel - MINUS javascript

Exploring the possibility of creating a spin the wheel effect like this using only HTML and CSS, no Javascript involved Seeking references or examples to determine feasibility. ...

Facing an issue with AngularJS where I am able to retrieve data.data, but struggling to assign it to a scope variable

Currently, I am developing a website using AngularJS that retrieves questions and multiple-choice answers from an Amazon Web Services table. This data is used to dynamically create a prelab questions page. The http get request is functioning properly; when ...

What's the best way to make two buttons appear side by side on a webpage?

I need to have my two buttons, Update and Cancel, displayed next to each other on the same line. Currently, there is a gap between the two buttons as shown in the attached image. Below is the HTML code I am using: <div class="form_block span2"> ...

Leveraging PHP variables to determine the image location, implement an onclick function to cycle through the image gallery

I am facing an issue with a database query that is supposed to display multiple images. These images are stored in a PHP variable and shown one at a time using a JavaScript gallery with an onclick function to navigate through them. Unfortunately, the funct ...

Specifying Size of Icons in HTML and CSS

Displayed in the image below are 3 icons - 2 of them are the same size, while one (on the left) appears larger and uneven compared to the other two. https://i.sstatic.net/JtIov.png This snippet demonstrates the HTML code related to this section: < ...

Is the contact form confirmation message displaying too prominently?

I am currently troubleshooting two different forms on a website I'm developing, and I am unsure of the exact cause of the issue. Form 1: Form 2: When attempting to submit Form 1 without entering any information, an error message is displayed exactl ...

The radio button becomes unchecked when moving to the next fieldset

While developing a dynamic page using PHP and Laravel, I encountered a situation where I needed to add an additional radio button option to each card. Below is the code snippet for the card in question: <div class="card" style="margin:10p ...

Combination of AngularJS and jQuery

I have a page in which additional input fields are dynamically added based on the selection made in a drop-down menu. This page is powered by angularjs, but I had to use jQuery specifically for adding these extra input fields. Here is the HTML code snippe ...

"Executing a query on Angular Firestore using the where clause fetches all documents from the

I am encountering a perplexing issue with my angular app that is connected to Firestore. Despite following the documentation closely, when I query for documents in a collection based on a specific condition, the array returned contains every single documen ...

Usage of double quotation marks in jquery formbuilder is not permitted

I am currently utilizing jQuery Formbuilder to create forms and saving the JSON data to a database. When editing the formbuilder, I retrieve the data as shown below: var options = { formData: '<?php echo str_replace("'","\'",$fo ...

adjusting dimensions of swf file within html code

I am trying to insert a small speaker icon from the following url: . However, when the flash is loaded, the dimensions of the swf file exceed those specified in the html tag. How can this issue be resolved? <div style="display: inline;float:center;"& ...

What could be causing the fluctuation in the length property of my array-like object?

Currently, I am following a JavaScript tutorial that covers the call and apply methods. One thing that has me puzzled is the behavior of an 'array-like object' used in one of the examples: var arrayLikeObj = { 0: 'Marty', 1: 78 ...

Building Dynamic Forms with AJAX, PHP, jQuery, and MySQL

Although this question may seem basic, I've spent an entire afternoon trying to debug it without using any IDE other than Sublime. I would greatly appreciate any help and hope to format this question in a beginner-friendly way once it's resolved. ...

Easily validate your email with this straightforward form. Completely puzzled

Today's challenge is tackling the email validation form issue. While searching for a solution, I stumbled upon an interesting code snippet: http://jsfiddle.net/jquery4u/5rPmV/ dyingOverHere(); The code seems to work flawlessly in the demo provided. ...