The header remains fixed while scrolling - troubleshooting the If Else statement

Check out this cool pen...

http://codepen.io/jareko999/pen/bZXbWP

The jQuery code adds a .fixed class to the #header when it reaches or goes below 0, but doesn't remove it when back above 0. I'm new to JS and struggling to understand what's causing this issue. Any help would be appreciated. Thanks.

Here's the HTML:

<div class="content">
  <div id="header"></div>
</div>

CSS for reference:

body {
    overflow-x: hidden;
    margin: 0;
}

#header {
    width: 100%;
    height: 80px;
    background: blue;
    z-index: 1;
}

.content {
    position: absolute;
    top: calc(100% - 80px);
    width: 100%;
    height: 200vh;
    background: linear-gradient(to bottom, red, yellow);
}

.fixed {
    position: fixed;
    top: 0;
    width: 100%;
    background: blue;
}

Included jQuery snippet:

$(window).scroll(function() {
    var top = $('#header').offset().top;
    var headerTop = (top - $(window).scrollTop());

    if (headerTop <= 0) {
        $('#header').addClass('fixed');
    } else {
        $('#header').removeClass('fixed');
    }

});

Answer №1

In order to create a sticky header, I discovered that I needed to retrieve the parent div's offset().top instead of using the actual header element itself. Below is the finalized scroll function that creates a sticky header based on the top position of a parent element.

Check out the code here

$(window).scroll(function() {
    var top = $('.content').offset().top;
    var headerTop = (top - $(window).scrollTop());

    $('#header').toggleClass('fixed', headerTop <= 0);
    console.log(headerTop);
});

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

`Vue Component failing to display data from Blade File`

In my project using Laravel Blade, I am currently in the process of converting some blade files to Vue components. One challenge I encountered is trying to display a dynamically created page title on the screen from the Vue component rather than the blade ...

What is the process for including a class on a div element?

I have written a code that displays a series of images in a sequence. Once the last image appears, I want to switch the class from .d-none to .d-block on the div Can this be achieved? onload = function startAnimation() { var frames = document.getE ...

Guide to animate the appearance of a div from a specific location

I have a div that smoothly slides out when a label is hovered over. HTML: <div class="cellDataViewTdmStatus divCell userSitesCol7"> <label class="lblViewTdmStatus">View Status</label> </div> <div id="tdmStatus" class="hid ...

Issue with inserting data into MySQL database using Node.js (JavaScript)

I am attempting to utilize the insert function but keep encountering an error. I want to add a user's name to the user table. The function I am using is: function insert(tableName, toField, value){ connection.connect(); var queryString = "i ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...

Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code? Sample Controller.js Code: oknok.controller('listagemController', function ($scope, $http) { $scope.init = function () { ...

Top-notch loading icon using jquery

Recently, I embarked on the journey of learning Javascript and jQuery simultaneously, and to my surprise, it feels quite manageable. As I delve deeper into creating functions, I am currently working on displaying a loading image. While I initially used on ...

Performing an HTTP GET request to an endpoint within a RESTful API

I am looking to integrate a feature in my web application that displays the list of online users on my website. To achieve this, I need to make an HTTP GET request to the URL which returns the user data in JSON format. The returned JSON data contains var ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Retrieve and utilize the dynamically produced values from the application's app.js in a script that is accessed using

In my Express.js Node web app, I generate a string in app.js during initialization: // app.js var mongourl = /* generated based on process.env.VCAP_SERVICES constant */; There is a script that I import into app.js using require(): // app.js var db = req ...

Issue with AngularJS $http not responding to ng-click after first call

My landing controller uses a service that initiates the $http call by default when the App loads. However, I need to pass parameters based on click events, so I implemented an ajax call on ng-click. The issue is that I keep receiving the same data on ng-c ...

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

The setInterval function for the automated image slider is experiencing issues and is not functioning properly

I am facing an issue where the third photo in the slider does not appear initially. Eventually, the slide fails completely, causing the photos to change rapidly. Strangely, after the slide fails, the third photo sometimes appears sporadically. I am puzzl ...

RxJS BehaviorSubject allows you to retrieve the current value or obtain a new one depending on a specific condition

I am managing a subject that consumers subscribe to: private request$: Subject<Service> = new BehaviorSubject(null); Upon initialization, my components utilize this function: public service(id: number): Observable<Service> { return this. ...

Server-side props become inaccessible on the client side due to middleware usage

I'm attempting to implement a redirect on each page based on a specific condition using Next.js middleware. Strange enough, when the matcher in middleware.ts matches a page, all props retrieved from getServerSideProps for that page end up being undef ...

What is the best way to end a table row after every group of four items?

I am working with a Handlebars template to display an array of movies in a table with four columns. Currently, I have set up a HBS helper in my code: app.engine('handlebars',exphbs({ defaultLayout: 'main', helpers: { n ...

Node interprets string as an object

I encountered the following code: <a class="btn-primary btn" href="/employer/booth/<%= user._id.toString() %>" <% console.log(typeof user._id, user._id) %> target="_blank"> Preview your booth </a> Upon running this ...

Artwork - Circular design disappears without warning

While working on a clock project purely for enjoyment, I noticed that the minute arc disappears from the canvas as soon as a new minute begins. Any idea why this is happening? Check out the clock in action: https://jsfiddle.net/y0bson6f/ HTML <canvas ...

Issue with record count in JqGrid after performing a search

Currently, I am utilizing jqgrid version 4.4. My goal is to determine the total number of rows in the grid. The following code is working well and accurately providing me with the record count: var Count = ($("#grid").jqGrid('getGridParam', &a ...