The persistent activation of a jQuery scrollTop function

My goal is to use jQuery to create a sticky header div (with position: fixed) once it's scrolled past a certain point.

This code has been working well for me:

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

    if (y >= 200) {
        $('.top').addClass('sticky');
    } else {
        $('.top').removeClass('sticky');
    }
});

However, I wanted to improve the user experience so I began experimenting with jQuery UI. Here is where I encountered an issue:

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

    if (y >= 200) {
        $('.top').toggle('fade', 200, function() {
            $('.top').addClass('sticky', function() {
                $('.top').toggle('fade', 200);
            });
        });
    } else {
        $('.top').removeClass('sticky');
    }
});

The desired behavior is for the div to fade out, become sticky, and then fade back in. However, it seems to be continuously toggling the fade effect.

Can someone offer advice on how to achieve the intended behavior? I want it to trigger once it's scrolled past the specified point, rather than constantly reacting to the scroll position.

Thank you.

Answer №1

It seems like the animation is getting stuck in a loop because it keeps triggering as you scroll. To resolve this issue, you will need to halt the animation.

var y = $(this).scrollTop();

if (y >= 200) {        
    $('.top')
        .stop(true, true)
        .fadeOut(200).delay(200)
        .fadeIn(200).addClass('sticky');
} else {
    $('.top').removeClass('sticky');
}

Check out jQuery's .stop() method for more information.

Feel free to view a live demonstration here.

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

Disabling modal popup buttons in Bootstrap 4 using Javascript

JSFiddle DEMO: https://jsfiddle.net/2yx16k8L/ I'm encountering an issue with my JS code. I want a click on a div to open the entire content within it. However, this action is causing the modal button in the dropdown to stop working. How can I resolve ...

Difficulties encountered when attempting to populate a select dropdown with data fetched through an AJAX request

Currently, I am working on a small project that involves managing libraries. One of the tasks at hand is populating a select tag with all the libraries stored in my database. To accomplish this, I have developed a WebService which features a web method cal ...

Tips for adjusting the header color in materialize framework?

I've been working on a web template and I'm looking to customize the color displayed in the Android browser (maybe using JS?). The default color is blue. How can I go about changing it? https://i.sstatic.net/RxLbS.jpg Appreciate any help! ...

Keep moving the box back and forth by pressing the left and right buttons continuously

Looking to continuously move the .popup class left and right by clicking buttons for left and right movement. Here is the js fiddle link for reference. This is the HTML code structure: <button class="right">Right</button> <button class="l ...

Malfunctioning jQuery Plugin

Currently attempting to implement a jQuery plugin to achieve a pagination effect similar to The plugin I came across is linked at Although the usage seems straightforward, I am encountering difficulties making it function correctly. Displayed below is t ...

Refreshing is not necessary when submitting a form using Ajax to post data

Initially, I find myself torn between using method or type, where if I define the method in the form, do I still need to define it in the ajax call? If not, why does ajax return undefined in the console? Furthermore, the code below triggers a 405 POST met ...

The slider in ZoomIn and ZoomOut does not adjust the zoom level from the center of the image

When using the d3 force layout ZoomIn and ZoomOut with a slider, the zoom doesn't start from the center. Instead, it moves from left to right. However, when using the mouse wheel, the zoom does start from the center. To see an example, please visit th ...

Having trouble understanding why the border-radius attribute is not being applied to tables?

I've been trying to give the outer corners of tables a rounded appearance in HTML/CSS, but I can't seem to get the border-radius property to work properly. After inspecting the elements in Chrome's computed section, I noticed that the eleme ...

Attempting to adjust the navbar dimensions, alter the size of the font, and align the text in the center

I need help with creating a responsive navbar for my website. I have been working on the CSS to adjust the size of the navbar and align the text properly, but I'm struggling to get it right. Here is a snippet of the CSS: .nav { font-family: "Ind ...

Creating a fixed column with DataTables in Bootstrap 4 and applying transparency to it within a

When using the DataTables example here, I noticed that when scrolling the table to the left, the fixed cell becomes transparent on dark rows. Could this issue be related to Bootstrap 4 or DataTables? If so, is there a workaround available to fix it? ...

What is the best way to hide the select arrow in an input-group using Bootstrap 4?

Is there a way to get rid of the unsightly double arrow in the select element? I have tried various solutions I found online, but none seem to be effective. <div class="form-group"> <label for="date">Date</label> <d ...

Issue with alignment in the multiselect filter of a React data grid

In React Data Grid, there is a issue where selecting multiple filter options messes up the column headers. Is there a solution to display selected filter options above a line in a dropdown rather than adding them to the column header? The column header siz ...

Flip an image by analyzing the colors beneath it

Looking for a way to invert the color of specific areas under a mask (PNG) for a floating menu. Rather than inverting all at once, I want only certain parts to be inverted underneath the mask. Is this achievable, or is there another approach I should consi ...

Extracting data with Jquery Repeater in jQuery

A repeater has been implemented using html/js, utilizing this helpful library. Currently, the goal is to extract data upon user clicking a button (work in progress). However, the challenge lies in accessing the data within elements like ingredienten[0][wa ...

NarrativeTome Hook for React

After incorporating the useLocation hook into my code, I encountered a hurdle in initializing it within Storybook: let location = useLocation(); const parsedLocation = new URLSearchParams(location.search) const query = parsedLocation.get('query' ...

Using C# objects as the main nodes in a JSON structure

I am attempting to send a Json object that I want to retrieve from jquery as, jdata.comType the c# code I am using is as follows, var frontChartList = new List<object>(); frontChartList.Add(new { comType = com ...

The importance of .hash in this jquery function explained

I utilized a jQuery function from someone else and tweaked it to fit my needs, however, I am struggling to grasp how it actually operates. Specifically, the line var content = this.hash.replace('/', ''); Can anyone offer an explanation ...

Are there any methods I can employ to maintain the traditional aesthetic while incorporating modern elements into web forms?

My current webforms application was built using visual basic, but now the user wants to migrate it to a new UI with Bootstrap and modern styling. The goal is to apply a side navigation bar and upper navigation bar while preserving the old pages and their o ...

Inject a jQuery form submission using .html() into a div element

I am currently working on developing a basic forum where users can view listed topics and have the option to add new ones on-the-fly by clicking a link or image. How can I detect and handle the form submission event for the dynamically added form within an ...

Learn how to implement a forced download feature in Symfony2 when using an Ajax call that returns JSON

I'm currently working on creating a download link for a file in Symfony2. While the file does download successfully, I've encountered an issue specifically in Chrome where it doesn't seem to work properly. I'm unsure of how to resolve ...