The sticky navigation bar is experiencing functionality issues

Here is the code I am using to ensure that the navigation bar sticks to the top of the page after scrolling:


var nav=$('body');
var scrolled=false;
$(window).scroll(function(){
    if(175<$(window).scrollTop()&&!scrolled){
        nav.addClass('stuck');
        $('.navigation-class').animate({marginTop:80},1000);
        scrolled=true;
    }
    if(175>$(window).scrollTop()&&scrolled){
        $('.navigation-class').animate({marginTop:0},0,function(){nav.removeClass('stuck');$('.navigation-class').removeAttr('style');});
        scrolled=false;
    }
});

The issue arises when the user quickly scrolls up and down while the navigation is still animating. This causes a hiccup effect in the menu when it suddenly jumps into its designated position.

You can try scrolling this page quickly to see this happening live.

Is there a way to make this animation run smoothly like on other websites?

I would appreciate any help or suggestions regarding this matter.

Answer №1

Upon revisiting the question, it appears that the issue may lie in not stopping the animation when the user scrolls back above 175px.

It seems like you are using position: float on your navigation element. Have you considered removing the float as soon as the user scrolls up?

You could experiment with setting the queue option to false (refer to https://api.jquery.com/animate/) so that the animation does not wait for others to complete.

Have you thought about replacing the JQuery animation with CSS transitions instead?


Perhaps this approach might work:

var nav=$('body');
var scrolled=false;
var scrollToggle = function(){
        $(window).off('scroll');
        if(175<$(window).scrollTop()&&!scrolled){
            nav.addClass('stuck');
            $('.navigation-class').animate({marginTop:80},1000, function() {
                $(window).on('scroll', scrollToggle);
            );
            scrolled=true;
        }
        else if(175>$(window).scrollTop()&&scrolled){
            $('.navigation-class').animate({marginTop:0},0,function({
                nav.removeClass('stuck');
                $('.navigation-class').removeAttr('style');
                $(window).on('scroll', scrollToggle);
            });
            scrolled=false;
        }
};

$(window).on('scroll', scrollToggle);

I have a similar setup in my Work In Progress. I've made some minor edits before sharing it here, hoping it could benefit you as well.

var headerFloat = function() {
            //Header
        var pageHeader = $('#pageHeader'), pos = '',
            headerMain = $('#headerMain'), headerMainHeight = '',
            content = $('#content'), contentPadding = '',
            pageTitle = $('h1.currentPage'), pageTitleTop = '';

        if($(window).scrollTop() >= 95) {
            pos = "fixed";
            headerMainHeight = '75px';
            contentPadding = '225px';
            pageTitleTop = '55px';
            contentHeaderTop = '130px';
        }

        //Header
        pageHeader.css('position', pos);
        headerMain.css('height', headerMainHeight);
        content.css('padding-top', contentPadding);
        pageTitle.css({ 'transition': 'all 0s', 'position': pos, 'top': pageTitleTop });
        pageTitle[0].offsetHeight; //force "reflow" of element -- stackoverflow.com/questions/11131875/#16575811
        pageTitle.css('transition', '');
    };

$(document).ready(function() {
    /* *** SCROLL -> FLOAT HEADER *** */
    $(window).on("scroll.float", headerFloat);

});

Instead of using .removeAttr('style'), consider resetting to the original value by inputting '' (empty string) in the JQuery css function. Additionally, you might want to reconsider the use of the 'scrolled' boolean variable and its necessity based on the scrolling behavior.

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 ajaxForm function is failing to execute properly and is not providing any error messages

When trying to use jQuery ajaxForm, I encounter a strange issue. I am attempting to set up a form for file upload with progress percentage tracking. However, my ajaxForm function does not seem to be triggering at all. Below is the code snippet I am usin ...

react router 2 will display a 404 error when the requested page is not

Currently, I am utilizing react router version 2.8.1 and attempting to configure my custom 404 page for my single-page application (SPA). However, I am encountering issues in actually returning a proper 404 status code. My main goal is to prevent Google fr ...

Unable to display image source in viewport

Currently, I am working on developing a basic ionic app that interacts with an API that I have created. I am encountering an issue where all data is being displayed correctly in the view except for the src attribute of an image. When I use console.log to c ...

What is the best way to increase the spacing between inline-block elements?

Just to clarify, I am not looking to delete space between inline-block elements - rather, I want to insert it. My goal is to create a grid of menu items that can accommodate 2, 3, or 4 items per row, and I hope to achieve this using media queries. Is the ...

Ways to minimize the left-hand sidebar?

Seeking a method to create a collapsible left side panel without affecting any other elements on the website. Preferably with a smooth sliding animation instead of an abrupt pop-in and out effect. Check out my website here to see the panel in question You ...

Tips for resizing images to fit within a TD cell in an HTML table

Currently, I have an issue with the image display within a TD element. Despite setting a specific width for the TD, the image appears to be wider than intended. Could you offer a solution to this problem? ...

Discord.js: Merging strings while pushing to an array

I am currently updating an embed message to notify users who have "enlisted" in a list by reacting. However, I am encountering an issue where the strings from the entire array are getting combined when the length of the array reaches 2 before adding a new ...

Unique background image that perfectly aligns with the dimensions of a single full screen

Does anyone know how this webpage achieves the effect of having a full-screen background that ends when scrolling down? I have noticed that the picture of the desert always covers my entire browser screen but is not a typical full-screen background as it ...

What is the simplest method for a beginner to transfer form data from HTML to an email?

Currently I am in the process of developing a compact website and looking to design an HTML form that can send values to my client's email address. The snippet of code for the form is as follows: <form id="contact-form" method=" ...

Is the presence of a 'disabled' attribute on a non-input element enough to render your document invalid in HTML?

Originally intended for <input/> elements, the disabled attribute raises a question when applied to non-input elements. Could this potentially lead to document invalidation? ...

Is it possible to create this design using CSS?

I attempted to break away from the conventional square layout of the internet with this design, but I am struggling to utilize Z-index to layer the backgrounds effectively. Here is the current code: <!--############################################# ...

What is the best way to apply CSS max-left or min-left positioning to an absolute element?

I currently have an element with the CSS properties: position:absolute; left: 70%; Is there a way to restrict this element from moving more than 900px from the left side? Similar to max-width but for positioning? ...

Enhancing Nextjs performance for mobile devices

Greetings everyone, I am currently experiencing performance issues on mobile devices. Can anyone provide suggestions on how to enhance the following aspects? https://i.stack.imgur.com/bEmln.png ...

Tips for changing the size of a div using an absolute div position

Is it possible for the #parent div to resize based on the dimensions of the #child div (if the #child div is using position:absolute;)? Similar to how the #t_parent table resizes according to the size of the #t_child table. <div id="parent" style="pos ...

java printwriter not cooperating with javascript

Hey there, I'm currently working on a webpage created from a servlet using PrintWriter. I'm adding HTML, CSS, and JavaScript to the page, but unfortunately, the JavaScript functions are not functioning properly. Could this be due to a syntax erro ...

Priority is given to strings over numbers

Here's some code I'm working with: <tbody> <tr> <td class="float-left"> <!-- {{selectedTemplat?.modifiedAt | da ...

Refreshing pane content within Kendo UI Splitview

I am utilizing the Kendo UI splitview. In my setup, I have configured one pane on the left for navigation and another pane on the right for content display. The left pane contains 4 navigation links structured as follows: <div data-role="pane" id="si ...

What is the best way to assess HTML enclosed by <td> tags returned by a method in an Angular application?

I'm facing an issue with a method in my .ts file that is supposed to dynamically generate HTML code for buttons within a td tag. However, when I use <td>{{actions(rec1)}}</td>, instead of getting dynamic buttons, the HTML gets printed as h ...

Utilize the Jquery Datatable responsive plugin within a collapsed panel of Bootstrap 3

Encountered an issue while integrating a Jquery Datatable (with its own responsive plugin) in a collapsed panel within bootstrap 3. Example that functions correctly: http://jsfiddle.net/Wc4xt/1804/ Example that is not functioning as expected: http://jsfi ...

Exploring the possibilities of integrating JavaScript with Flash technology

Currently, there is a simple Flash project in development that connects to an RTMP server and streams video and audio from a webcam. The project allows users to create a stream with a specific name. This project also features an input for entering a strea ...