Stable header that jumps to the top when scrolled

I have implemented the JavaScript code below to set the header to a fixed position when it reaches the top of the page so that it remains visible while the user scrolls. Everything appears to be functional, but the header movement is abrupt and not smooth. What am I overlooking? You can test it live here:

$(function(){
    // Check the initial Position of the Sticky Header
    var stickyHeaderTop = $('#headerWrapper').offset().top;

    $(window).scroll(function(){
        if( $(window).scrollTop() > stickyHeaderTop ) {
            $('#headerWrapper').css({position: 'fixed', top: '0px'});
        } else {
            $('#headerWrapper').css({position: 'static', top: '0px'});
        }
    });
});

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>Martin Izehi</title>
    <meta name="description" content="" />
    <meta name="keywords" content="">

    <meta name="viewport" id="viewport" content="width=device-width, minimum-scale=1.0, user-scalable=0, maximum-scale=10.0, initial-scale=1.0" />
    
    <link rel="shortcut icon" href="assets/elements/favicon.ico">
    <link rel="stylesheet" type="text/css" href="assets/css/reset.css">
    <link rel="stylesheet" type="text/css" href="assets/css/core.css">
    ...

CSS:

body {
    background: #000000 url('../elements/background.png') no-repeat center top;
    line-height: 125%;
    text-align: center;  
    overflow-x: hidden;
    ...

Answer №1

Instead of using position: static;, opt for position: absolute;

$(function(){
        // Determine the initial position of the Sticky Header
        var stickyHeaderTop = $('#headerWrapper').offset().top;

        $(window).scroll(function(){
                if( $(window).scrollTop() > stickyHeaderTop ) {
                        $('#headerWrapper').css({position: 'fixed', top: '0px'});

                } else {
                        $('#headerWrapper').css({position: 'absolute', top: '0px'});

                }
        });
  });

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

Tips for including shared information across different ionic tabs

Is there a way to include some shared content, like a canvas, in between the content of different tabs in Ionic? I want this common content to be displayed across all tabs, while each tab still shows its own dynamic data below it. I attempted to add the c ...

Measuring dimensions with HTML on the server - how to do it?

I am facing a challenge with my web application that allows users to upload entire .html files to the server. I am looking for a way to automatically detect and store the width/height of the uploaded html in my database. Currently, I have been experimenti ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

Is it possible to utilize CSS rules for a non-existent div within CSS?

Can this be achieved using CSS? If .div1 is not present, enforce the following rule: .div2{ property: value; } For example, <div class="div1"> ... </div> <div class="div2"> <!-- it exists, so no action needed --> </div& ...

The parameter 'string | JwtPayload' cannot be assigned to the parameter 'string'

Utilizing Typescript alongside Express and JWT for Bearer Authorization presents a specific challenge. In this situation, I am developing the authorize middleware with JWT as specified and attempting to extricate the current user from the JWT token. Sampl ...

Centered Fixed Upward Scrolling Div

Currently facing a challenge with my project involving a chat interface created in Angular. I am struggling with the CSS styling as the chat starts at the top and scrolls downward off-screen as the conversation progresses. Although I can scroll along with ...

Utilize a singular ajax function to handle various events with personalized data parameters

Could someone help me with this specific issue? Here is an explanation. Let's say I have a function called load_window() and various events like clicks, changes, etc. How can I properly create a custom_data variable in these events and use it in the ...

Tips for eliminating the left and bottom border in a React chart using Chart.js 2

Is there a way to eliminate the left and bottom borders as shown in the image? ...

Difficulty with Line Breaks in Spans

I've noticed that my multi-line address in the footer is not breaking correctly at certain screen widths. Each line of the address is enclosed within a <span> tag with a specific class and then styled either as block or inline-block in the CSS ...

Steps to fully eliminate the recent action panel from Django's administrative user interface

Is there a way to completely remove the recent action panel from Django admin UI? I have searched extensively but all the information I find is about clearing the data in the panel from the database. What I'm looking for is a way to entirely eliminate ...

How to Assign List Load to Controller for Google Maps?

I find myself in a predicament where I am required to retrieve the list in my Controller, but currently I am utilizing a Kendo Grid to fetch the list that will be utilized in my Google Maps. Now, my questions are: How can I directly associate the Load ...

Using a custom attribute in jQuery allows conditional statements to be executed using the

I have been attempting to create an if/else statement in jQuery using a custom attribute called "data-id". I decided to name it this way because I thought I could utilize the .data() method in jQuery, but unfortunately, it did not work as expected. Below ...

Using the Nodejs Array prototype filter method within a JSON object

Attempting to create a function that filters and returns specific strings within JSON data. Any advice is appreciated. Thank you! [ { line: '{"status":"waiting"}' } ] var body_W = []; body_W.push({line: JSON.stringif ...

Why does AngularJS treat $http response.data as an object, even though PHP sends back a JSON string?

I am struggling with an AJAX call to PHP. The Angular code seems simple: $http( { // ... } ) .then( function cf_handle_success( response ) { console.log( response.data ) ; // --> [object Object] } , ...

Looking to sanitize an array of objects in Node.js? If you find that manually iterating through it only returns 'object Object', there are alternative methods to properly

I have a collection of items structured like this: var data = [ { msg: 'text' }, { src: 'pic.jpg',id: 21,title: 'ABC' } ]; My goal is to cleanse the values by manually iterating throug ...

I have a website hosted on Heroku and I am looking to add a blog feature to it. I initially experimented with Butter CMS, but I found it to be too pricey for my budget. Any suggestions on

I currently have a website running on Heroku with React on the front end and Node.Js on the back end. I want to incorporate a blog into the site, but after exploring ButterCMS, I found the pricing starting at $49 to be too steep for my budget. My goal is ...

What is the best way to fetch d3 data from a service?

I've been exploring a tutorial on creating charts with d3, which can be found at: When it comes to loading data for use in d3, I typically rely on the following code snippet: d3.tsv("data.tsv", type, function(error, data) { The file "data.tsv" is c ...

Custom AngularJS directive fails to reflect changes in model after selecting a file

I recently created a custom directive called ng-file-chosen, which is supposed to capture the selected file name from an <input> element and bind it to the ng-model passed in. In the code snippet below, the result of ng-file-chosen is linked to mode ...

`Three.js and its efficient use of JavaScript for enhancing performance``

Deep within the Object3D code lies: rotateX: function () { var v1 = new THREE.Vector3( 1, 0, 0 ); return function ( angle ) { return this.rotateOnAxis( v1, angle ); }; }(), But what about: rotateX: function (angle) { var v1 = new ...

Prevent the routing on page reload in AngularJS

My route provider setup looks like this: app.config(function ($routeProvider, $locationProvider){ $locationProvider.hashPrefix(''); $routeProvider .when('/', { templateUrl: 'login.html', controller: 'loginCtrl&a ...