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

I'm curious about the origin of this.on event handler. Is it part of a particular library or framework?

While casually perusing through the application.js file in the express source code, I stumbled upon this interesting piece of code. I'm curious about the origin of this '.on' event. Is it part of vanilla JavaScript or is it a feature provid ...

React: executing function before fetch completes

Whenever I trigger the ShowUserPanel() function, it also calls the getUsers function to retrieve the necessary data for populating the table in the var rows. However, when the ShowUserPanel function is initially called, the table appears empty without an ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

vuejs function for modifying an existing note

Method for editing an existing note with Vue.js in a web application This particular application enables users to perform the following tasks: Create a new note View a list of all created notes Edit an existing note Delete an existing note Prog ...

The user authentication is not recognized in the current session (Node.js, Express, Passport)

I have encountered an issue where req.user is undefined, despite my efforts to troubleshoot for over 4 hours. I even resorted to copying and pasting the server/index.js file from a friend's server, modifying the auth strategy to suit my own, but the p ...

What is the best way to implement a scrollbar in a specific div rather than the entire window?

Hey everyone! So, I have this window in electronJS with a div where I'm dynamically adding elements using Javascript and the function --> document.createElement('section'). Here's the loop in Javascript to add these elements: for ( ...

Error Parsing JSON using jQuery

I am encountering a Parse Error while working with valid JSON, even though I have validated it on jsonlint. The data is fetched from a MySQL database using PHP and converted into a JSON string before being retrieved in jQuery (refer to the code below). B ...

Looking to perform an Ajax call to update a Rails model using HTML5 contenteditable, but encountering an issue where it creates a new

I am in need of assistance to update the plots of a story using HTML5 contenteditable feature. Below is the code snippet: Refer to file# for editing multiple plots <div id="editable" contenteditable="true"> <%= simple_format p.description %&g ...

Edit content on the fly using ajax (add information to database)

I have a question that pertains to both UX and technical aspects. I am currently creating a list using ajax and PHP. I am unsure whether it is advisable to manipulate the DOM before the backend processes are complete. What potential issues could arise if ...

Numerous sections with tabs on the webpage

I am in need of incorporating multiple tabbed sections on a single page, but unfortunately they are currently interconnected. When one tab is clicked, it impacts the others. To see this issue in action, you can visit: https://jsfiddle.net/pxpsvoc6/ This ...

Encountering the "Error: JSON.parse: unexpected character" when trying to retrieve JSON data using AngularJS

I've been struggling with this issue for the past few days. Every time I attempt to fetch a JSON object using Angular's $http.get method, I encounter the error message "Error: JSON.parse: unexpected character". The JSON data is generated using P ...

What is the best way to obtain the true dimensions of an HTML element?

Is there a way to determine the dimensions of a <div> element in order to accurately position it at the center of the browser window? Additionally, which browsers are compatible with this method? ...

Generating a hierarchical structure of JSON data through iterative looping

Currently, I am in the process of creating a directive within Angular to assist with field validation. The functionality is working smoothly until it comes time to store the validation result. My objective is to store this information in an object structu ...

Achieve SEO excellence with Angular 4 in production settings

I am currently building a website using Angular 4 as part of my personal study project. Although my website is live, I realized that it's not SEO friendly. After making some changes, I came across a valuable resource on server-side rendering in Angul ...

Is the && operator being utilized as a conditional statement?

While following a tutorial, I came across this code snippet that uses the 'and' operator in an unusual way. Is this related to React? Can someone provide an explanation or share documentation that clarifies it? {basket?.length > 0 && ...

Can you determine the sequence in which these code statements are placed on the call stack?

I am a beginner in the world of Javascript and currently seeking to grasp a better understanding of how the JS execution engine operates. I am aware that any asynchronous code statement is pushed onto the call stack and then promptly removed, allowing it t ...

Single-use binding format

I am a beginner with Angular and I have some doubts about the syntax used in Angular. In AngularJS, we can achieve one-time binding like this: <p>{{::myVar}}</p> In Angular, I know we can do it differently. <p [innerText]="myVar"></ ...

"Step-by-step guide on setting up Angularjs ng-model in a Rails environment

Question regarding the utilization of two-way binding in AngularJS and Rails ERB files. Let's say the input value in my .erb file has an initial value like this: example.erb <input type="text" value=" <%= @item.title %> " ng-model ="item.t ...

Image overlay on a hovering background

I'm currently facing a challenge with creating a hover effect for a background image while keeping the image in front unchanged. I would like the background to darken on hover, but I want the image in front of it to remain the same. Essentially, I ne ...

The height of the Material UI Paper component is not appropriately matched with the parent component

I am currently working with the Paper component that contains a Card component, and I am trying to make its height fill the entire screen. To simplify the problem, I have provided the following code: import React from "react"; import { makeStyles ...