Prevent content from occupying unnecessary space below a sticky div

When the "link" on the sticky header is clicked in this scenario, how can I ensure that the linked content item (#mypara) appears below the sticky div rather than directly underneath it where it may be hidden?

$(document).ready(function() {
    $(window).scroll(function() {
        var distanceFromTop = $(document).scrollTop();
        if (distanceFromTop >= $('#header').height())
        {
            $('#sticky').addClass('fixed');
        }
        else
        {
            $('#sticky').removeClass('fixed');
        }
    });
});
body { margin: 0px; background-color: #e3e3e3; }
#header { background-color: #cb5454; height: 140px; }
#sticky {
    background-color: #546bcb;
    height: 70px;
}
#sticky.fixed {
    display: block;
    position: fixed;
    top: 0;
    width: 100%;
}
p[id] {
  color:red;
  /*padding-top: 170px;*/
}
#footer { background-color: #cb5454; height: 140px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header">header</div>
<div id="sticky">sticky <a href="#mypara">link</a></div>
<div id="section">
...
... (truncated for brevity)
...
<p>section </p>
<p>section </p>
</div>
<div id="footer">foot</div>

This particular fiddle was attained from discussions on other SO threads, suggesting that using 'position:fixed' for a sticky div after scrolling is a common approach since 'position:sticky' did not yield the desired results.

https://i.sstatic.net/7iFvi.png

The image above highlights the desired positioning when the link is clicked.

Answer №1

When working with the scroll function, start by fetching the current position of the scroll using window.pageYOffset. After that, you can utilize the scrollTo(x, y) method of the window. For the y value in the scrollTo, subtract the height of your div from the window.pageYOffset. In other words, it would be (window.pageYOffset - height of your div)

Answer №2

`

$(document).ready(function() {
        $(window).scroll(function() {
            var distanceFromTop = $(document).scrollTop();
            if (distanceFromTop >= $('#header').height())
            {
                $('#sticky').addClass('fixed');
            }
            else
            {
                $('#sticky').removeClass('fixed');
            }
        });
    });
// New code snippet for scrolling to #mypara with 150px offset
$('a[href*=\\#]:not([href$=\\#])').click(function() {
    event.preventDefault();
    $('html, body').animate({
        scrollTop: $($.attr(this, 'href')).offset().top - 150
    }, 500);
});
body { margin: 0px; background-color: #e3e3e3; }
    #header { background-color: #cb5454; height: 140px; }
    #sticky {
        background-color: #546bcb;
        height: 70px;
    }
    #sticky.fixed {
        display: block;
        position: fixed;
        top: 0;
        width: 100%;
    }
    p[id] {
      color:red;
      /*padding-top: 170px;*/
    }
    #footer { background-color: #cb5454; height: 140px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="header">header</div>
    <div id="sticky">sticky <a href="#mypara">link</a></div>
    <div id="section">
    <p>section 1</p>
    <p>section 2</p>
    <p>section 3</p>
    <p>section 4</p>
    <p>section 5</p>
    <p>section 6</p>
    <p>section 7</p>
    <p>section 8 x</p>
    <p>section 9</p>
    <p id="mypara">section 0 xxxx</p>
    <p>....(remaining content not shown)....</p>
    
    <p>section</p>
    <p>section</p>
    <p>section</p>
    </div>
    <div id="footer">foot</div>

`

Answer №3

According to Jean-Marc Zimmer, the use of Sticky eliminated the need for javascript, although it still presented an issue with the element appearing underneath the sticky div.

To address this problem, a pseudo element was added:

p[id]::before {
  content: "";
  display: block;
  height: 60px; /* fixed header height*/
  margin: -60px 0 0; /* negative fixed header height */
}

You can view the complete example on this fiddle link: http://jsfiddle.net/paull3876/8m3qwont/14/

Please note that position:sticky does not function in IE11.

Additionally, adding padding or a border to p[id] (outside of ::before) will interfere with this effect. The reason behind this behavior remains unknown!

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 data labels in a scatter plot using d3.js

I am currently studying d3.js for data visualization and I have chosen to work with the titanic dataset My objective is to incorporate passenger names into my visualization so that when a cursor hovers over a point, the person's name is displayed. H ...

Getting the json array value and populating it in a dropdown list in angularjs - a step-by-step guide!

{"id":1,"firstName":"John1","lastName":"Doe1","**accountIds**":[12345,12346,12347],"recipients":[{"accountNumber":22222,"firstName":"Mary1","lastName":"Jane1"},{"accountNumber":33333,"firstName":"Mary2","lastName":"Jane2"}]} Show the "accountIds" as a dro ...

Can we activate or attach a jQuery UI event?

Similar Question: jQuery AutoComplete Trigger Change Event After successfully implementing the jQuery UI Autocomplete widget using version 1.9, I am curious to know if it is possible to trigger or bind a jQuery UI event. For example, can the jQuery UI ...

When the onInput event is triggered, React renders components and console.log() displays different values

When I type in the input field, it triggers the onInputChange() function. This function updates the state of inputValue, and then calls the getValue() function which retrieves the current state of inputValue and logs it to the console. However, the value d ...

Error: Namespace declaration does not have a type annotation - TypeScript/Babel

After creating my app using the command npx create-react-app --typescript, I encountered an issue with generated code and namespaces causing Babel to throw an error. Here are the steps I took to try and resolve the issue: I ejected the project Updated b ...

Utilize Antiforgery Protection in ASP.NET Core Alongside JQuery

I am currently using JQuery in conjunction with ASP.NET Core 1.0.1 and implementing the following Ajax call: $("#send-message").on("submit", function (event) { event.preventDefault(); var $form = $(this); $.ajax({ url: "api/messages", dat ...

Utilize jQuery to create a dynamic image swapping and div showing/hiding feature

I'm having trouble implementing a toggle functionality for an image and another div simultaneously. Currently, when the image is clicked, it switches to display the other div, but clicking again does not switch it back. Can someone please advise on wh ...

Managing websites on Android when the keyboard is displayed

I am currently facing an issue with my webpage on Android (Galaxy SIII). The problem occurs when visitors try to enter their email in the form at the bottom of the page. The keyboard becomes visible, causing the design to look messy. When using Chrome, the ...

How can I create walls in ThreeJS using a path or 2D array?

I am faced with the task of creating a 3D house model, specifically the walls, using a 2D path or array that I receive from a FabricJS editor that I have developed. The specific type of data being transferred from the 2D to 3D views is not critical. My in ...

I am interested in updating the content on the page seamlessly using Angular 6 without the need to reload

As a newcomer to Angular, I am interested in dynamically changing the page content or displaying a new component with fresh information. My website currently features cards, which you can view by following this Cards link. I would like to update the page ...

Guide on converting this function into a computed property within Vue

Is it possible to concatenate a fixed directory path, which is defined in the data property, with a file name that is determined using v-for? I encountered an issue when attempting to do this using a computed property. The error message displayed was: ...

Guide to positioning a button on top of another button using Vuetify

I'm facing an issue where I want to add a button on a clickable card, but clicking the button also triggers the card click event. Here's my current code snippet: <v-card @click="show = !show"> <v-img src="https://cdn.vuetifyjs.com/im ...

JavaScript function to evaluate true conditions

I am encountering an issue while calling sub functions connected to if statements within my main function. Even though the sub functions are supposed to return true or false, the expected alerts are not appearing. if (functionAAA()){ alert("111 ...

Guide on aligning text along a baseline

CLICK HERE TO ENTER THE INTERACTIVE PLAYGROUND HTML: <div class="first">Text A</div> <div class="second">Text B</div> CSS: div { background-color: rgba(255, 0, 0, 0.3); /* For visualization only */ margin-top: 50px; ...

Angular Component - Array missing initial value in @Input property

Having trouble transferring values between components? I'm currently dealing with a situation involving two components: report-form and comment-form. The report form contains an array of comments, displaying a list of comments and a button for each on ...

Using CSS :hover for elements with dual classes only

Is there a way to make the CSS :hover selector work only when two different classes are attached to a div? I have tried a couple of methods, but they eliminate the hover effect. For example: .accordionButton .cyan:hover{ color: cyan; } I cannot s ...

jQuery blur unless

I would like to implement a feature where a div is hidden when a text box loses focus, except if the user clicks on a specific div. If the user clicks on that particular div, then the action of losing focus should not trigger the hiding of the div with cla ...

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Click to load additional data until the list has reached its full length

<ng-container *ngFor="let item of itemList | slice:0:3"> <mat-checkbox>{{item}}</mat-checkbox> </ng-container> <div> <button id="loadMore">Load More</button> </div> I wo ...

Disregard periods in URLs when configuring nginx servers

While developing with Vite in development mode via Docker on my Windows 10 machine, I encountered an issue where the local custom domain would not load due to a required script failing to load. The specific script causing the problem is /node_modules/.vit ...