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

Tips for retrieving a flag when there is a preexisting record within an association in Sequelize

I am working with a model A that has a 1:N association with a model B. My objective is to retrieve all records from A and determine whether there is at least one associated record from B (true) or not (false). The relationship setup: ModelA.hasMany(ModelB ...

Experiencing issues with Errors when Targeting ES5 in Angular2 TypeScript?

In my development environment, the npm version is 3.10.10, and I want to create a new Angular2 project from scratch. When I try running npm install angular2 --save I encounter this error message: Error Image After referring to this answer which recomm ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

An advanced template system incorporating dynamic scope compilation

My project requires a unique solution that cannot be achieved with standard data-binding methods. I have integrated a leaflet map that I need to bind with a vue view-model. While I was able to display geojson features linked to my view, I am facing chall ...

Is there a way to restrict the number of words displayed in React? Check out this code snippet: `<ProductImg imgtext={products.description}/>`

imgAlt={product.name} Note: Consider the product name as: HD Single Sided Cantilever Rack. In this case, only HD Single Sided... should be displayed Please find the code snippet below <ProductImg imgtext={products.description}/> ...

What is the alternative to jQuery.submit now that it has been deprecated in version 3.3?

After reviewing the source code, you will find: /** * Attach an event handler to the "submit" JavaScript event, or trigger that event on an element. * * @param handler The function to be executed each time the event is triggered. * @see {@link https:/ ...

Troubleshooting: Resolving issues with Vue's global EventBus in my project

I am using Vue.js within a Laravel project and I am encountering an issue with the global event bus. I have created an event-bus.js file and imported it where needed. Although events are being generated upon clicking, there seems to be no reactions from th ...

Dealing with unique constraint violation in Mongodb when using insertMany

Currently, I'm in the process of working on a project that involves using node.js and mongodb version 5. In my collection, I have implemented a unique index for the Parcel property. However, during testing, an error is triggered: MongoBulkWriteError: ...

Refresh the html of the contenteditable element with the most recent targeted information from the textarea

One issue I'm encountering is quite straightforward: selecting/focusing on a few contenteditable elements, then selecting the textarea and changing the HTML of the last focused element from the textarea. However, my problem arises when the textarea tr ...

Exploring ways to customize the styles of MUI Accordion components in a Next.js project using CSS modules

I'm trying to customize the default MUI CSS for the accordion component using a CSS module. The issue I'm facing is that the class is dynamically added by MUI, making it impossible to target directly. Here's the solution I attempted, but it ...

Error Uploading File - Functioning in Postman but not on website interface

I'm currently pursuing the full stack certification on devchallenges.io and tackling the authentication app challenge. So far, I've successfully implemented the login and register functionality, as well as fetching the logged-in user's infor ...

firefox is experiencing lag issues with react-spring and framer-motion

Encountering an issue with two animation libraries, react-spring and framer-motion. Attempting to create a basic animation that triggers upon the component's initial visibility (simplified version). <motion.div initial={{x: -25, opacity: 0}} anima ...

Easy steps to launch Excel application with an HTML button using a web browser

How can I create a button on an HTML page that will launch an Excel application when clicked by the user? <button class="btn btn-primary" onclick="window.open('excelApplication.url','_blank')">Launch Excel</button> ...

Node.js and Express facing challenge with Stripe checkout functionality

I am encountering an issue while attempting to integrate stripe into my checkout process. When I click on the checkout button, instead of being directed to the checkout page, I receive the following message: {"url":"https://checkout.stripe.c ...

Failure to update the DOM after clicking a button and making an AJAX request

After experimenting with different iterations of this code, the outcomes have been mediocre and inconsistent. The concept is rather simple: A user inputs a search query into a text box, clicks a button, and the query is assigned to a var search. This varia ...

Execute the code only if the variable is not null

I encountered an issue with my code: setInterval(function() { $.ajax({ url: url, success: function(data, count){ var obj = jQuery.parseJSON(data); var content = obj.results[0].content; }}) }, 2000) The code runs every 2 seconds an ...

There seems to be a disconnect between the CSS and HTML files

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JavaScript Basics</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="c ...

The initiation of an AJAX request in Android appears to be unsuccessful

My code for retrieving JSON data from the server doesn't seem to be working. There are no logs in logcat coming from "log.v". I also feel like my try-catch statements are not effectively handling errors all the time. I am using a query for the ajax re ...

Show different values in Array arranged in Table format with the help of Ajax code

Check out the code I have attempted below: <script type="text/javascript"> $('#doctorselected').on('change', function(e){ console.log(e); var doctorid = e.target.value; var url = '{{URL::to('getdoc ...