Switching between fixed and unfixed divs causes two absolute divs to alternate

I am currently working on a code to keep a fixed div ("two") in place between two absolute positioned divs ("one" and "footer") while scrolling.

However, there is an issue that arises when the browser window is resized. The distance between the footer and the point where the fixed div ("two") becomes unfixed either increases or decreases. This causes the fixed div to become unfixed before it reaches the footer or after it has already passed it.

Does anyone have any suggestions on how to address this problem?

Check out the DEMO here.

UPDATE (21 JULY 2016):

It appears that the issue stems from the fact that the width of the "leftside" div is set as a percentage. When the browser window is resized, the "leftside" div adjusts its height accordingly based on the content within it. As a result, the fixed position of div "two" remains static relative to the initial page load position.

I need to maintain the responsiveness of the design without reloading the page when scaling the browser window due to other functions on the website. Although refreshing the page after resizing does reset everything correctly, reloading is not a viable option for me.

Possible solutions include:

  1. Is there a way to dynamically reset the lowest possible position of div "two" upon window resizing?
  2. An even better approach might be to automatically and frequently reset the lowest possible position of div "two" whenever the user interacts with the webpage or scales the browser window. Given that collapsible segments within the "leftside" div can alter its height without adjusting the browser window size directly.

It seems like modifications may be required in this portion of the script(?):

$window.resize(function()
    {
        bumperPos = pos.offset().top;
        thisHeight = $this.outerHeight();
        setPosition();
    });
    $window.scroll(setPosition);
    setPosition();
};

Below is the complete script:

var window = this;

$.fn.followTo = function (from, bumper) {
    var $this = this,
        $window = $(window),
        $from = $(from),
        $bumper = $(bumper),
        $startPos = $from.offset().top + $from.height(),
        bumperPos = $bumper.offset().top,
        thisHeight = $this.outerHeight(),
        setPosition = function(){
            if ($window.scrollTop() < $startPos) { 
                $this.css({
                    position: 'absolute',
                    top: $startPos
                });
            } else if ($window.scrollTop() > (bumperPos - thisHeight)) {
                $this.css({
                    position: 'absolute',
                    top: (bumperPos - thisHeight)
                });
            } else {
                $this.css({
                    position: 'fixed',
                    top: 0
                });
            }
        };
    $window.resize(function()
    {
        bumperPos = pos.offset().top;
        thisHeight = $this.outerHeight();
        setPosition();
    });
    $window.scroll(setPosition);
    setPosition();
};

$('#two').followTo('#one', '#footer');

Answer №1

I've implemented three key changes:

  • Renamed the pos variable to bumper as it was erroneously labeled.
  • Added a reset for $startPos on resize to address issues with elements above the sticky element changing dimensions when resized.
  • Refactored the fixed element's positioning logic by introducing a parameter in the followTo function, enhancing the transition between fixed and absolute positions.

Check out the updated JSFiddle.

$.fn.followTo = function (from, bumper, fixedOffsetTop) {
    var $this = this,
        $window = $(window),
        $from = $(from),
        $bumper = $(bumper),
        $startPos = $from.offset().top + $from.height(),
        bumperPos = $bumper.offset().top,
        thisHeight = $this.outerHeight(),
        setPosition = function(){
            if ($window.scrollTop() < $startPos - fixedOffsetTop) { 
                $this.css({
                    position: 'absolute',
                    top: $startPos
                });
            } else if ($window.scrollTop() > bumperPos - thisHeight - fixedOffsetTop) {
                $this.css({
                    position: 'absolute',
                    top: (bumperPos - thisHeight)
                });
            } else {
                $this.css({
                    position: 'fixed',
                    top: fixedOffsetTop
                });
            }
        };
    $window.resize(function()
    {
        $startPos = $from.offset().top + $from.height();
        bumperPos = $bumper.offset().top;
        thisHeight = $this.outerHeight();
        setPosition();
    });
    $window.scroll(setPosition);
    setPosition();
};

$('#two').followTo('#one', '#footer', 30);

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

Issues arise when attempting to insert data into an HTML file using PHP

Good evening, I am having a problem where when I attempt to use PHP to replace "hello world" in an HTML file, it ends up completely empty each time. Can anyone point out what mistake I might be making? Here are the HTML and PHP files: <!DOCTYPE html&g ...

Unable to retrieve JSON data using jQuery

When working with jQuery to retrieve JSON data, I encountered an issue. After storing the data in a variable named "ajaxResponse," attempting to access specific data points resulted in an error stating that ajaxResponse.blah is not defined. Interestingly, ...

Steps for clearing input field with type=date in Protractor:

I am currently working with protractor version 4.0.4 and I'm encountering an issue where I cannot clear a date input field. It seems like Chrome is introducing some extra controls that are causing interference. You can find further details about Chro ...

Pause until the array is populated before displaying the components

Currently, I am using firebase storage to fetch a list of directories. Once this fetching process is complete, I want to return a list of Project components that will be rendered with the retrieved directory names. How can I wait for the fetching to finish ...

Express fails to pass password validation

I encountered an issue with a ValidationError stating that the Path password is required while attempting to register a new User. My experience in Node, programming, and authentication is limited. Below is the code for the User model and schema where I ma ...

What are some key considerations for creating a website that is optimized for printing?

I am working on creating a website filled with content that I want to optimize for printing. My goal is to have the content easily printable without any unnecessary elements like navigation or advertisements. To achieve this, I am considering using two sep ...

Encountering the issue of receiving an undefined value for a variable despite having previously defined it within

I’ve been working on implementing the Google Maps distance matrix API with the google-distance-matrix library. Here’s the code snippet I’m using: app.get("/users", (req, res) => { // console.log(req.query); // res.send(req.query); ...

Tips for retrieving the location of a draggable waypoint in the Google Directions output

<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Location Partner</title> <!--styles for ...

Utilize the $post parameter when sending data in AngularJS

Trying to send Handsontable table data using $http POST with Angular.js has been a bit of a struggle for me. Here's the code snippet: var $container = $("div#table"); var handsontable = $container.data('handsontable'); $scope.sa ...

Using Jquery to create HTML elements from a C# function

I have a C# web service method that creates HTML code and returns it as a string. I want to take this HTML string from the method and replace a specific div element. function updateHTML(ID) { var gID = ID; $.ajax({ type: "get", co ...

The issue with flexslider not functioning properly arises when used in conjunction with ajax Magnific popup

Having trouble integrating flexslider into magnific popup as the script inside the popup is not functioning properly. The magnific popup is being loaded using the wordpress function wp_enqueue_script(): jQuery(document).ready(function($){ $(&apo ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Execute a zoom out action by pressing the (Ctrl) and (-) keys simultaneously in Javascript

I'm trying to figure out how to simulate a Ctrl - zoom out using Javascript. I've noticed that using the style zoom property or the transform property gives different results with white space in the corners, rather than the smooth zoom out effect ...

What is the purpose behind certain developers specifying font size twice using different units?

When creating website themes, I often come across developers defining properties twice with different units. For example: body, button, input, select, textarea { color: #404040; font-family: sans-serif; font-size: 16px; font-size: 1rem; ...

What could be causing my component to not refresh when used as a child?

I have been experimenting with some code to track rerenders. The initial approach failed when passing <MyComponent> as a child component. it("should return the same object after parent component rerenders", async () => { jest.useF ...

Basic calculation of movement yields inaccurate outcome

I am encountering an issue with this specific function implementation. Calculations.add(this, //CONTEXT function () { //CALUCATE this.position.x += (this.movementSpeed.x / 10); }, function () { //HAVE CALCULATED ...

Creating an element that remains fixed once it reaches a distance of 50px from the top of the screen

Hey there! I'm working with an html div element that currently scrolls along with the page, but I was wondering how I can make it become fixed once it reaches a distance of 50px from the top of the screen. Any ideas on how to achieve this? Just to pro ...

Applying a class to an element in VueJS is not functioning as expected

My goal is to assign the class .testcolor to the div element when testvalue is true, and apply no class when it's false. I encountered an issue where the getClass method does not get called when added to :class attribute, but works fine when called f ...

Whenever I attempt to start the server using npm run server, I encounter the following error message: "Error: Unable to locate module './config/db'"

This is the server.jsx file I'm working with now: Take a look at my server.jsx file Also, here is the bd.jsx file located in the config folder: Check out the db.jsx file Let me show you the structure of my folders as well: Explore my folder structur ...

Adjusting the Size of a DIV Container

I'm currently working on a website project and I am in need of incorporating a resizable panel similar to the ones found on jsfiddle or hotmail (hotmail's left panel contains emails while the right content panel allows you to read those mails.) ...