Incorrect .offset().top calculation detected

Within a webpage, I have multiple sections. Positioned between the first and second section is a navbar menu. As the user scrolls down and the navbar reaches the top of the page, a function is triggered to fix it in place at the top. While this functionality generally works well by calculating the offset during scrolling, there are instances where an incorrect value is reported, causing the navbar to flicker.

Below is the custom CSS class:

.sticky {
position: fixed;
top: 0;}

and custom JavaScript code:

var checkStickyMenu = function() {
    if ($(window).scrollTop() > $("#secondary-nav").offset().top ){ 
$("#secondary-nav").addClass("sticky")
} 
else { 
if ($("#secondary-nav").hasClass("sticky")){
$("#secondary-nav").removeClass("sticky");
}}}
$(window).on("scroll", function() {
checkStickyMenu();
console.log("scroll " + "win scroll: " + $(window).scrollTop() + " secnav: " + $("#secondary-nav").offset().top);
})
checkStickyMenu();

The console.log() displays:

custom.js:16  scroll win scroll: 1010.8571 secnav: 377.98209999999995
custom.js:16 scroll win scroll: 1011.4286 secnav: 1011.4286
custom.js:16 scroll win scroll: 1018.8571 secnav: 377.98209999999995
custom.js:16 scroll win scroll: 1031.4286 secnav: 1031.4286
custom.js:16 scroll win scroll: 1053.1428 secnav: 377.9820333984376
custom.js:16 scroll win scroll: 1067.4286 secnav: 1067.4286
custom.js:16 scroll win scroll: 1070.8572 secnav: 377.98213896484367
custom.js:16 scroll win scroll: 1071.4286 secnav: 1071.4286

Observing the log, you can notice that the offset value jumps from the correct value of 377 to values around 10XX, causing the navbar to lose the 'sticky' class.

Answer №1

Check the scroll event trigger, particularly focusing on the last 3 lines in the console log:

When the scrollTop value is 1067.4286 and the offset of the navbar matches at 1067.4286, then scrolling to a new position where scrollTop becomes 1070.8572, the navbar will also update to 1070.8572 since it's fixed. This causes your checkStickyMenu function to remove the "sticky" class from "#secondary-nav", making the navbar unfixed with a new offset value of 377.98213896484367.

During the subsequent scroll event, with scrollTop at 1070.8572 and the navbar offset at 377.98213896484367, the checkStickyMenu function adds the "sticky" class back to "#secondary-nav", restoring it to its previous fixed state akin to when scrollTop was 1067.4286.

This cycle continues indefinitely due to an issue stemming from an incorrect algorithm.

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

Conceal the div class upon clicking it

I'm dealing with a list of videos and I need to hide the class when it's clicked. Check out this sample HTML output: <div id="primary-video"> <iframe id="video" width="100%" height="auto" src="https://www.youtube.com/embed/test" fra ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

What could be causing npm to not recognize my module in the "require" statement?

Currently, I am in the process of developing an npm module and conducting tests before making it available to the public. The method I am following is outlined in a blog post found at this link. However, I am encountering difficulties when trying to requir ...

What is the best way to change the orientation of a vector map?

Is there a straightforward method for rotating a vector-based map on CANVAS in order to integrate it into a browser navigation system? ...

Is it possible to resize a div based on the width of the window?

Imagine a scenario where it's not possible to change the content of a div, but only its shape and size by using transform: scale(1.4) for instance. To better understand this concept, take a look at This Website and try resizing the window using brows ...

What is the process for incorporating linear-gradient coloring into the background of a Material UI Chip component?

Is it possible to incorporate a linear-gradient below color as a background for Material UI Chip? linear-gradient(to right bottom, #430089, #82ffa1) The version of Material UI I am working with is v0.18.7. <Chip backgroundColor={indigo400} style={{widt ...

Tips on implementing .on() with querySelector in jquery?

Can you help me convert the jQuery code below into a querySelector method? <script type="text/javascript"> jQuery(function($){ $('#woocommerce-product-data').on('woocommerce_variations_loaded', function() { $ ...

Navigating through various folders to access files in HTML

I am facing an issue with my folder structure and includes in my PHP files: index.php includes/header.php includes/conn.php contents/ad_list.php contents/ad_posting.php In my index.php, I successfully included includes/header.php. However, in contents/a ...

Troubleshooting: Clicking the Ajax button yields no response

I’ve looked through all the similar questions and tried multiple solutions, but nothing seems to be working. My goal is to retrieve job postings from my database related to careers. When a user wants to apply for a job, they should click a button which w ...

Interacting with an MVC controller via Ajax for sending and retrieving data

I am having an issue with my code where the parameter 'a' in my controller is always null. Can anyone help me figure out what I'm doing wrong? Here is the code snippet: View: <input type="text" id="zipcode" /> <script src="http: ...

What steps do I need to follow in order to create an AJAX application that functions similarly to node

As someone new to ajax, I am facing challenges while trying to create a forum software similar to nodebb. Despite having developed a php forum previously, its outdated appearance prompted me to seek alternatives like nodebb for a more modern look and feel. ...

Implementing JavaScript Code in TypeScript

Every JavaScript code should also be valid in TypeScript, but when attempting to run the following code snippet below, an error is triggered. Could someone convert this JavaScript code into TypeScript? Error: 20:9 - TS2531 Error: Object is possibly 'z ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

Activate the file upload window when an option is chosen from the dropdown menu

Is there a way to automatically trigger the file input when "UploadStudents" is selected from the dropdown menu? Dropdown Menu <select name="performaction" id="performaction"> <option value="">- Actions -</option> <option value=" ...

Is there a way to create a JavaScript function that relies on a successful form submission?

After attempting to modify a post on Stack Overflow, I am facing issues with my JavaScript code. As a beginner, it's possible that I overlooked something in the code causing it not to work as expected. The project I'm working on involves creatin ...

Protecting Angular Routes: Verifying HTTP-Only Cookie Authentication on the Server- CanActivate Function

I am utilizing an HTTP only cookie for authentication in my server: export const checkCookie = async (req: Request, res: Response) => { const token = req.cookies["token"]; if (!token) { return res.status(401).json({ message: "Unau ...

Unlocking the Mystery of Capitalizing Strings with jQuery Classes

I came across this code online, but it does not appear to be functioning correctly. Could the syntax be the issue? The code is located at and pertains to names that need to be capitalized. However, the strings are currently in all uppercase, so I need to ...

Employ the symbol ""q" within a repetition sequence

When trying to retrieve data from a Mssql server, I encountered an issue with a function that contains a loop. The function returns some data to the callback, and now I need to figure out how to store this data from kriskowal's "q" into the resultset ...

What is the preferred method for writing `*zoom: 1;` in CSS?

Trying to create my code, I decided to borrow some CSS files from older code. However, upon running yarn build I encountered several errors like: ▲ [WARNING] Expected identifier but found "*" [css-syntax-error] <stdin>:122:2: 122 │ * ...

ng-repeat dysregulating the binding of directive models

<input-directive model="config.shared.product.whatevers[0]"></input-directive> <!-- This code is functioning correctly, however the following does not bind properly --> <td ng-repeat="whatever in config.shared.product.whatevers trac ...