Issues arise with the functionality of the sticky navigation script following a browser resize

I recently came across a jQuery script for sticky navigation that I've implemented on a website.

$(function() {

    // get the initial top offset of the navigation 
    var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;

    // determine whether the navigation bar should have "fixed" css position or not
    var sticky_navigation = function(){
        var scroll_top = $(window).scrollTop(); 

        if (scroll_top > sticky_navigation_offset_top) { 
            $('#sticky_navigation').css({ 'position': 'fixed', 'top':-23, 'left':0 });
        } else {
            $('#sticky_navigation').css({ 'position': 'relative', 'top':-30 }); 
        }   
    };

    sticky_navigation();

    $(window).scroll(function() {
        sticky_navigation();
    });
});

Unfortunately, the script only functions smoothly if I do not resize the browser after loading the site. When I resize, the script does not account for the new size and the navigation bar moves to different positions while scrolling. I attempted to add

$(window).resize(function() {
    sticky_navigation();
});

but it did not resolve the issue.

It seems like updating the top offset after a resize is necessary. Since I am not well-versed in programming, any suggestions with code examples would be greatly appreciated.

I hope someone can provide assistance.

EDIT: Link to example on jsfiddle: http://jsfiddle.net/p9Lvbz68/8/

Answer №1

Start off by defining sticky_navigation_offset_top inside the sticky_navigation function, not outside of it.

Next, make sure to utilize

$(window).on('scroll resize',function() {

This means your code should look something like this:

$(document).ready(function() {

    // the function that determines whether the navigation bar should have a "fixed" css position or not
    var sticky_navigation = function(){
        // get the initial top offset of the navigation 
        var sticky_navigation_offset_top = $('#sticky_navigation').offset().top;

        var scroll_top = $(window).scrollTop(); // current vertical position from the top

        // if user has scrolled more than the navigation bar, change its position to fixed to stick to the top, otherwise revert back to relative
        if (scroll_top > sticky_navigation_offset_top) { 
            $('#sticky_navigation').css({ 'position': 'fixed', 'top':-23, 'left':0 });
        } else {
            $('#sticky_navigation').css({ 'position': 'relative', 'top':-30 }); 
        }   
    };

    // execute the function on page load
    sticky_navigation();

    // and run it again every time you scroll
    $(window).on('scroll resize',function() {
        sticky_navigation();
    });
});

Answer №2

Have you considered the impact of setting 'top':-23 in your CSS on the mathematical calculation in the if condition? Scrolltop cannot be lower than the offset when the offset is negative, and the lowest scrolltop value is 0 (I have not verified if this is the actual behavior).

Try running these statements in the console:

Console.log(scroll_top); Console.log(sticky_navigation_offset_top);

Especially after this line of code:

var scroll_top = $(window).scrollTop();

Observing the message log in the console while scrolling after resizing should help you test this theory.

However, it's still unclear why this works prior to resizing...

------- Update ---------

Upon reviewing your fiddle, the jumping issue may stem from making an element fixed, thus removing it from the layout flow. Consequently, the content shrinks, causing a noticeable jump on the page.

Here's an example for clarity: http://jsfiddle.net/snn0xj4h/. I added a top margin to the header to compensate for the jump (not the ideal fix, but it could be a temporary solution).

    if (scroll_top > sticky_navigation_offset_top) { 
        $('#sticky_navigation').css({ 'position': 'fixed', 'top':"-23px", 'left':0 });
        $('#header').css("margin-top", $('#sticky_navigation').height());
    } else {
        $('#sticky_navigation').css({ 'position': 'relative', 'top':"-30px" }); 
        $('#header').css("margin-top", 0);
    }

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

Creating a dynamic Bootstrap navigation bar using PHP

I created a website using bootstrap, but now I want to add more dynamic features. The tutorial I'm following for this does not involve the use of bootstrap. Am I missing something obvious here? Could you please review my code? (To avoid overloading t ...

What steps should be taken to ensure that data can be transmitted from the input without allowing the user to edit the ID field?

Here is the sample HTML: <form action="/app02/user_edit-{{obj.id}}/" method="post" > <input type="text" name="id" value="{{obj.id}}" disabled> <input type="text" name="username" value="{{obj.username}}"> <i ...

Reformat a table in Asp.Net Bootstrap to ensure optimal display on mobile devices through a media query,

I came across this code on the following website: https://css-tricks.com/responsive-data-tables/, but unfortunately, it is not functioning as expected for my specific table within a Razor view. Here is the table code that I am using: <table class=" ...

Hierarchy in CSS: The battle between author and user styling

Following a hierarchy of precedence: User agent declarations User normal declarations Author normal declarations Author important declarations User important declarations The CSS specification distinguishes between author and user: Author. The author s ...

What is the best way to upload a profile picture to the header of my website?

Looking to customize my home page by adding a profile picture on the left side of the navigation panel. Can anyone guide me on achieving this using only HTML and CSS, without the need for JavaScript? I want the image to be displayed at the top left corn ...

Set up an event listener for all buttons to detect clicks, and proceed to initiate an AJAX request to

Looking for a way to incorporate jQuery into my HTML code. Specifically, I want to create a function that triggers an Ajax post request to retrieve the value of an iframe and append it to the following div: <div id = "contenedorFrame"></div> ...

Utilizing JQuery AJAX for Effortless Caching with PHP Endpoints

I am currently working on improving the speed of the ajax requests on my website. The site operates using live filtering, so when a user interacts with a form element, the data will adjust accordingly. While the functionality works well, I find that it&apo ...

Increase the font size of the text inside a table cell without altering the cell's width

Let me clarify my query with some images. This is how my current setup looks: https://i.sstatic.net/tyelv.png Everything is contained within a table, where the boxes span the width of the table. However, I need the data field to expand across the full sc ...

What defines a quick or sluggish load time when it comes to a webpage?

Recently, I constructed a webpage with multiple JavaScript elements incorporated. I am wondering what constitutes a fast load time versus a slow one. Currently, my load time is averaging around 490ms with four different JavaScript components. Is this con ...

Unveiling and Shifting Among Concealed HTML Forms

After going through numerous tickets with similar questions, I still can't seem to achieve what I want. So, I have no choice but to ask this question myself. I currently have an HTML page with 2 forms and 2 buttons. Both forms are initially hidden us ...

The alignment of input boxes is off

Apologies for the somewhat vague title, I struggled to come up with a more accurate description of my issue. Here is a basic HTML form: <html> <FIELDSET> <DIV> <SPAN class="label">Label 1</SPAN> <DIV ...

Struggling with PHP variables and AJAX JavaScript

Hey everyone, I've made some edits and have a new question regarding a similar issue. On test.php in my Apache server, I have a PHP script that connects to a database and retrieves data from a table. <?php $con = mysqli_connect("localhost", "user" ...

Issue with scrolling feature in div

I am currently facing an issue with scrolling on my website. Visit this site to see the problem. When scrolling down, it causes the "hidden" part of the site to slide up. I want to achieve a similar sliding effect, but it needs to be smooth. I have attempt ...

jquery personalized auto-suggest

I have multiple input[type="text"] elements with the class .autocomp. When I search for something, PHP retrieves data from a MySQL database and displays it in HTML format using jQuery. My question is, what is the most effective approach among these option ...

Storing user input from Vue.js in a JavaScript array for future use

Utilizing vue.js <template> <input id="email" v-model="email" type="text" placeholder="Email"> <input id="name" v-model="name" type="text" placeholder=" ...

Animating slides with CSS Keyframes and React, incorporating toggle slide fade out and slide fade (back) in

I am seeking a solution for toggling a box (div) with slide-out animation and then sliding back in animation (in reverse) upon button press. My requirement is to have no animations during the initial page render. While I can successfully slide the box to ...

The cropper fails to load within the image element inside a modal pop-up

Utilizing fengyuanchen's cropper library, I am cropping an uploaded image and then submitting it to a form. <div id="change-dp" uk-modal> <div class="uk-modal-dialog uk-modal-body"> <button class="uk ...

Creating a stationary navbar and sidebar with Bootstrap for your website

Is there a way to make the navbar and sidebar fixed when the user scrolls down the page without altering their design? I need them to be responsive as well. Can anyone assist me with this using bootstrap? Here is my fiddle: https://jsfiddle.net/exyvat08/17 ...

Difficulty with spacing in HTML/CSS styling

Here is what I'm currently working on: link to jsfiddle code * { margin: 0; padding: 0; } html { height: 100%; } header, nav, section, article, aside, footer { display: block; } body { font: 12px/18px Arial, Tahoma, Verdana, sans- ...

Tips on adjusting video to the screen size

I am looking to create a fullscreen video for my webpage. I originally used an image as a cover, but now I want to switch to using a video. You can check out my old code on this link. Below is my new video code: <div class="embed-responsive embed-resp ...