Sticky box fails to maintain position as header scrolls

I am looking to create a Sidebar that sticks to the window while scrolling, but stops when it reaches the footer. I have managed to get it partially working, but there is a small issue that I can't seem to solve.

Test it live here:

Everything seems fine until you scroll; the sidebar sticks to the top of the page but remains hidden behind the fixed header. How can I prevent it from being hidden behind the header and position it correctly? Is there a way to add smooth animation to it?

Here is the HTML:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="utf-8" />

        <title>LOAI Design Studio</title>
        <meta name="description" content="LOAI Design studio"/>
        <meta name="keywords" content="">

        <meta name="viewport" id="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=10.0, initial-scale=1.0" />

       // No changes made in the remaining HTML code...

    </body>
</html>

The CSS:

/*Portoflio Project Page*/
#portfolio-projectPage{
    text-align: left;
    position: relative;
}

// No changes made in the CSS code...

And Finally The JavaScript bit:

$(function() {
    $.fn.scrollBottom = function() {
        return $(document).height() - this.scrollTop() - this.height();
    };

    var $StickyBox= $('.detailsBox');
    var $window = $(window);

    $window.bind("scroll resize", function() {
        var gap = $window.height() - $StickyBox.height() - 10;
        var visibleFoot = 255 - $window.scrollBottom();
        var scrollTop = $window.scrollTop();

        if(scrollTop < "auto" + 10){
            $StickyBox.css({
                top: (200 - scrollTop) + "px",
                bottom: "auto"
            });
        }else if (visibleFoot > gap) {
            $StickyBox.css({
                top: "auto",
                bottom: visibleFoot + "px"
            });
        } else {
            $StickyBox.css({
                top: 0,
                bottom: "auto"
            });
        }
    });

Answer №1

Your if(scrollTop < "auto" + 10) condition will always return false because "auto" + 10 is a string.
Please update your code as follows:

if(scrollTop < 80){
    $StickyBox.css({
        top: (130 - scrollTop) + "px",
        bottom: "auto"
    });
}

I have adjusted the values to achieve the desired behavior.

Furthermore, in the final condition, change top: 80 to position it below the header:

else {
    $StickyBox.css({
        top: 80,
        bottom: "auto"
    });
}

Edit: improved code

var gap = $window.height() - $StickyBox.height() - 10;
var visibleFoot = 255 - $window.scrollBottom();
var scrollTop = $window.scrollTop();

if(scrollTop < 50){
    $StickyBox.css({
        top: (130 - scrollTop) + "px",
        bottom: "auto"
    });
} else if (visibleFoot > gap - 100) {
    $StickyBox.css({
        top: "auto",
        bottom: visibleFoot + "px"
    });
} else {
    $StickyBox.css({
        top: 80,
        bottom: "auto"
    });
}

Answer №2

While scrolling, the element with the class .detailsBox receives an inline style of

top: 0px; 

which causes it to appear as if it is 'sticking' to the header. It seems that there are frequent changes to the css top value in this code snippet:

if(scrollTop < "auto" + 10){
    $StickyBox.css({
        top: (200 - scrollTop) + "px",
        bottom: "auto"
    });
} else if (visibleFoot > gap) {
    $StickyBox.css({
        top: "auto",
        bottom: visibleFoot + "px"
        });
} else {
    $StickyBox.css({
        top: 0,
        bottom: "auto"
    });
}

It seems like these adjustments may not be necessary. The element already has a margin-top of 28px and its position is fixed, so it should always be in the correct position without additional modifications.

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

Can CSS be used to automatically focus on a div element?

Can CSS be used to set autofocus on a div element? <div class="form-group" style="margin-left:10px"> <label for="organizationContainer" class="nmc-label">@Res.GroupStrings.CreateNewGroupOrganization</label> <div id="organiza ...

What is the CSS method for styling a color label on an active input box?

I am trying to achieve a specific effect where the label changes color when the input box is in focus. However, my current CSS code does not seem to be working as expected. Can someone please explain why and provide a solution to fix this issue? .test-l ...

Discovering a particular string within a jQuery array object: Tips and tricks

One thing that is confusing me is the jQuery array object. To explain further: I have two arrays, one called brandsLink and the other called floorLink. When a user clicks on a link, I am saving the brand name in a variable called brandName, and then checki ...

Struggling to navigate a nested JSON API using NEXTJS?

I am facing difficulties while trying to extract nested JSON API data in NEXTJS. Specifically, I am struggling with extracting a dictionary within a dictionary from the API file. In the example provided below, I have only been successful in consuming entr ...

Example: Utilizing data transfer from model to directive

I have a question regarding a specific part in an example from Thinkster. I believe my confusion is due to my limited understanding of JavaScript and AngularJS fundamentals. I've been teaching myself since December, starting with the basics of JavaScr ...

Tips for enabling a flexbox item to extend beyond its container

While attempting to utilize flexbox for creating a navbar with the logo in the center, I encountered an issue where the logo wasn't able to overflow from above and below the navbar. I experimented with squeezing in and positioning the element, but it ...

What is the proper method for terminating an Express app.all?

Here's a snippet of my code where I utilize the app.all method. In this scenario, I am invoking the fetchBuildings function based on the building ID or hash provided in the URL. Subsequently, I am assigning values to the title, description, and image ...

Adding a class to the body depending on the tag or href that was clicked on the previous page

Currently, I am working on two pages - the "Home-Page" and the "Landing-Page". My goal is to customize the content of the "Landing-Page" based on the button clicked on the previous page (which happens to be the "Home-Page"). Initially, I tried using ancho ...

Adding Firebase Authentication to my AngularJS website

I am currently creating a school website using AngularJS. My goal is to incorporate account functionality through firebase authentication. However, I have limited experience with Javascript and find working with AngularJS and implementing firebase to be ...

Navigating through each segment

I'm currently working on a website with sections that are set to be 100% height of the window, but at least 800px tall. My goal is to implement a smooth scrolling functionality where one scroll moves the view from section to section. However, if the ...

Preview of webpage in Sublime Text is not rendering jQuery properly

I am encountering an issue while trying to set up a page with skrollr for parallax effect. It functions perfectly on platforms like CodePen, but when I attempt to preview it after setting up my page on Sublime Text, nothing seems to work. Could there be s ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

What is the recommended TypeScript type for setting React children?

My current layout is as follows: export default function Layout(children:any) { return ( <div className={`${styles.FixedBody} bg-gray-200`}> <main className={styles.FixedMain}> <LoginButton /> { children } ...

I'm having trouble centering the links in my navigation bar using flexbox, and I'm not sure how to fix it

Struggling with creating a navigation bar for my portfolio-building project. The "Who needs a quote" element is correctly displaying on the left, but I can't figure out how to center align the links "Sports, business, politics". Tried using flexbox op ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

Cloud Function scheduler incorporating dynamic memory allocation control

I am currently working on setting up a scheduled function in Firebase Cloud Functions that interacts with third-party APIs. However, I am facing an issue with the memory limit being exceeded due to the large size of the data processed by this function. Al ...

Response from the controller upon choosing a value from the selection dropdown

Scenario: In this scenario, there are two tables in consideration: Firm table : ID (string), Firm(string) Firms table: FirmID(string FK), Name(string) The goal is to select a value from the Firm table, pass it to the controller as Firm, and then execut ...

What could be the reason behind Typescript's unexpected behavior when handling the severity prop in Material UI Alerts?

Trying to integrate Typescript into my react project and encountering a particular error: Type 'string' is not assignable to type 'Color | undefined'. The issue arises when I have the following setup... const foo = {stuff:"succes ...

Struggling to figure out the correct method for aligning calendar using bootstrap-datetimepicker?

Struggling with aligning the calendar correctly under a textbox while using bootstrap-datetimepicker in a form? The positioning seems off, and the calendar icon isn't where it should be. It's not behaving like a simple datetimepicker as shown in ...

Cannot transfer variables from asynchronous Node.js files to other Node.js files

Is there a way to export variable output to another Node.js file, even though the asynchronous nature of fs read function is causing issues? I seem to be stuck as I am only getting 'undefined' as the output. Can someone help me identify where I ...