Increasing space at the top with heading

As I scroll down, the header on my website remains in a static position and disappears. However, when I scroll back up, the header reappears wherever the user is on the page. While this functionality works well, I have noticed that as I scroll all the way to the top, my margins expand due to the header. Once it reaches the very top, the margin adjusts back to match the header's position.

In addition, there is banner image with an overlay on my site. If you scroll down and then back up, you will notice a change in margin caused by the image overlay. Additionally, the header appears 'fidgety' during this process.

How can I ensure that the margin always stays consistent and does not readjust?

var didScroll;
var lastScrollTop = 0;
var delta = 5;
var navbarHeight = $('header').outerHeight();

$(window).scroll(function(event){
    didScroll = true;
});

setInterval(function() {
    if (didScroll) {
        hasScrolled();
        didScroll = false;
    }
}, 250);

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('header').removeClass('nav-down').addClass('nav-up');
    } else {
            if (st < navbarHeight) {
            if (st === 0 || st < 1) {
            $('header').css('position', 'static');
          }
        } else {
            $('header').css('position', 'fixed');
        }
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('header').removeClass('nav-up').addClass('nav-down');
        }
    }

    lastScrollTop = st;
}


<header class="nav-down">
</header>


header {
    background: #F2F2F2;
    height: 120px;
    top: 0;
    transition: top 0.5s ease-in-out;
    width: 100%;
    z-index: 100;
    border-bottom: 1px solid #9C9C9C;
}
.nav-up {
    top: -123px;
}

Answer №1

The reason for this issue is that changing the position of the header to fixed causes the DOM to shift up by the same height as the header, as the header no longer affects the layout of the DOM.

To solve this problem:

You can add a margin-top with the same height as the header when applying position: fixed to your #service-img. Here's the code snippet (Please note, it has not been tested on live site):

function hasScrolled() {
    var st = $(this).scrollTop();

    // Make sure they scroll more than delta
    if (Math.abs(lastScrollTop - st) <= delta)
        return;

    // If they scrolled down and are past the navbar, add class .nav-up.
    // This is necessary so you never see what is "behind" the navbar.
    if (st > lastScrollTop && st > navbarHeight) {
        // Scroll Down
        $('header').removeClass('nav-down').addClass('nav-up');
    } else {
        if (st < navbarHeight) {
            if (st === 0 || st < 1) {
                $('header').css('position', 'static');
                $('#service-img').css('margin-top', '0px');
            }
        } else {
            $('header').css('position', 'fixed');
            $('#service-img').css('margin-top', '120px');
        }
        // Scroll Up
        if (st + $(window).height() < $(document).height()) {
            $('header').removeClass('nav-up').addClass('nav-down');
        }
    }

    lastScrollTop = st;
}

UPDATE:

I have tested this code on your website using Chrome DevTools, and it appears to work correctly. I hope this resolves your issue!

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

Avoid duplicate borders on columns that adjust their size based on the screen width

Picture yourself utilizing Bootstrap 4 and displaying various cells, each with unpredictable numbers. .cell { border: 1px solid black; } <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> < ...

Ways to programmatically compare all elements between two separate arrays

Is there a way to create a process where the first loop iterates through the elements of one array, while another loop goes through a second array and compares each element in the first array with all elements in the second array? For example: //first loo ...

Guide on setting up the installation process of Gulp jshint with npm?

Having trouble with the installation of JSHint. Can anyone point out what I might be doing incorrectly? This is the command I am using: npm install --save-dev gulp-jshint gulp-jscs jshint-stylish Getting the following error message: "[email protect ...

What is the best way to add prefixes to my SCSS style sheets?

After attempting to add prefixes to my scss files, I came across the autoprefixer tool. However, I discovered that it only supports CSS files. Is there a way to utilize autoprefixer with scss files? Here are the commands for Autoprefixer: npm install post ...

The JavaScript function's if and else statements are being executed simultaneously

Upon loading the page, I am checking the value of a dropdown. Strangely, when I debug, it appears that the controller is executing both the if and else statements, which should not be happening. /* Here is my code: */ $(window).load(function() { ...

Error encountered while trying to upload a file using PHP on a hosting platform

Hey everyone, I'm feeling really frustrated right now because I'm facing a file upload error in my PHP code. The issue is that the file is not getting uploaded to my folder and no error messages are being displayed. I've been working on cr ...

Converting Javascript game information into PHP

Once the player loses, I need their score to be updated in the database using PHP. There is a separate JavaScript class that runs the game, utilizing setInterval to check the index.php function and update the database if the player loses. However, the issu ...

Sending parameters within ajax success function

To streamline the code, I started by initializing the variables for the selectors outside and then creating a function to use them. Everything was working fine with the uninitialized selector, but as soon as I switched to using the variables, it stopped wo ...

Can I use more than one AudioContext at a time?

In my project, I am developing a React App using MeteorJS that utilizes the Web Audio API. This app consists of multiple pages, each of which utilizes web audio functionality. The issue I am facing is that I have hit the limit of 6 audio contexts allowed i ...

The Javascript regex allows for the presence of positive and negative numbers, with the option of a single minus symbol

oninput="this.value = this.value.replace(/[^-0-9.]/g, '') This code snippet is utilized in my current project. However, there seems to be an issue where the input can contain more than one minus sign, as shown here: ---23 To address this p ...

The transformation of a Raphael element does not occur as expected when it is passed to a function within a loop

My attempt to rotate an object by a variable number of degrees in order to mimic a dial was unsuccessful. Initially, I tried the following steps: window.onload = function() { var paper = new Raphael(document.getElementById('canvas_container ...

Unable to attach the script to recently added DOM elements

After spending considerable time working on this, I'm still unable to figure it out. You can find the page I am referring to at: The "show more" button at the bottom triggers additional posts to be displayed on the page using the following script: ...

Utilize either the success() or complete() method when making an AJAX call

Can someone please explain the AJAX call below, specifically focusing on the complete() method? I've noticed that replacing complete() with success() results in an empty responseText, similar to when using the AJAX error() method. However, if I keep ...

Using Tailwind @apply within an Angular application's CSS file

I've noticed a yellow line appearing under the @apply in my CSS files, even though the styles are being applied correctly to the HTML components. This seems to be happening in every CSS file I use. Can anyone shed light on this issue? Removing these ...

The proper method to retrieve the parent function parameter within an inner JavaScript callback function

Consider the code snippet below. var exec = require('child_process').exec; var extraInfo = {'test':1,'passing':'test'}; runWithData(extraInfo); function runWithData(passedData) { exec('/Users/test/Deskto ...

Tips for positioning buttons in a sticky footer

I've been trying to align buttons on the left, center, and right side but haven't had any success. How can I ensure that buttons are aligned properly on each side, even when adding more buttons? When adding more buttons to the left, I want them ...

What is the best way to transfer state information from a hook to be displayed in the App component in React

Is there a way to transfer the state(data) of info to the App hook, in order to showcase the properties within div elements? The function setInfo(info) saves the data intended for display on the Map hook and inspecting console.log(info) within _onClick rev ...

What causes JavaScript image to stop loading while displaying a prompt dialog?

I have nearly finished my project. I will include a codepen link at the end of the post for debugging purposes. What Should Happen? The img element has an id property of dragon, and the image specified in the src attribute should be pre-loaded as the defa ...

What could be causing the queuing of multiple Ajax requests in ExtJS?

I am encountering an issue with my grid setup. I have a menu on the left side for each item on the grid, and this menu's items change based on the selection in the grid. When the event selection is triggered, an Ajax.request function is called to hand ...

Is it possible to iterate through HTML form data using JSON arrays or objects?

I've been searching this website and the internet for a while now, trying to figure out how to save multiple arrays to my localStorage. I asked a question earlier which helped me progress a bit, but I'm still struggling to grasp the concept. I c ...