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

The width of the Div is set to 100%, yet there is still some empty space visible on

I am having trouble setting the background of my code to display a picture that is 300px in height and 100% in width. However, when I set the width to 100%, there are about 15px gaps on each side. I could adjust the width to 1000px, but that presents issue ...

Executing a JavaScript function to trigger a PHP script that saves data into a MySQL database

I have a button in my HTML file that, when clicked, should insert data into a database and then reload the page. I am calling a JavaScript function within the onclick event to handle this. Below is the JavaScript function: function grandFinale() { i ...

What is the method for passing an element object instead of an id in JSXGraph?

I'm attempting to modify var brd2 = JXG.JSXGraph.initBoard('box', {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); to read as var brd2 = JXG.JSXGraph.initBoard(this.$('#box'), {boundingbox: [-8.75, 2.5, 8.75, -2.5]}); Due to the creat ...

Exploring the World of Node.js Event Handling in JavaScript

After reviewing the provided code snippet: binaryServer = BinaryServer({port: 9001}); binaryServer.on('connection', function(client) { console.log("new connection"); client.on('stream', function(stream, meta) { console.log(& ...

What are the steps to create a shadow effect on a bar chart in ChartJs?

Currently, I am utilizing version 3.9 of chartjs to construct a bar chart. My goal is to incorporate a shadow effect on the bars resembling the image in this link: Despite my efforts, I have not been able to locate instructions on how to achieve this in t ...

Send key-value pairs to the function using ng-model

I am currently working on a functionality that involves extracting an object from json and displaying its key-value pairs using 'ng-repeat' in AngularJS. The form includes checkboxes where the value can be either true or false, determining if the ...

Enhance your dynamic php page with the use of a light box feature

Hey, I have created a PHP page that dynamically reads images from a folder and displays them on a gallery page. However, I am facing some issues - I am unable to link an external CSS file and I have to include all the CSS within the HTML. Additionally, I c ...

Tips for anchoring a row to the bottom of a Bootstrap webpage

After working with bootstrap, I am looking to position the last row of the page at the bottom in a fixed and responsive size manner. ...

Refresh Content Using Ajax with jQuery Mobile's Link Click or Browser's Back Button

Alright, I've exhausted all options, time to seek advice from the professionals! I'm dealing with a multi-page JQM app. index.html - serves as the starting point and retrieves a list of projects via Ajax, everything is functioning perfectly - g ...

The NextJS Link component does not seem to be receiving the styles from Tailwindcss

I am currently working on a nextjs frontend project that has tailwindcss integrated. Below is an example of the code I am using: import Link from 'next/link' return( <div> <Link className="text-sm hover:text-gray-600" ...

Mapping with Star Components

As a newcomer to ReactJs, my task is to create a 5-star review component with the ability to display half-star ratings. I previously implemented this in Angular5. Within the map method, I need to loop through the following elements: <!-- full star -- ...

Positioning absolute elements negatively in Firefox may cause unexpected behavior

I attempted to position an absolute element with a negative value, and it works perfectly in every browser except for Firefox. In Chrome, IE, or Safari, the blue handler box is correctly positioned in the middle of the top border. Is there a workaround to ...

Sending handlebars variable to the client-side JavaScript file

I am currently working on an application using node.js along with express and handlebars, and I'm trying to find a way to transfer handlebars data from the server to client-side JavaScript files. Here is an example: //server.js var person = { na ...

Automated file uploading with AJAX on Firefox

After inserting a row into the database, I want to automatically upload a PDF/XML file with no user involvement. The script should be able to identify the filename and location of the file. Is there a method to achieve this task? Share your ideas in the a ...

Unexpected issue with sliding menu toggle implementation

I have been struggling to make a menu slide to the left when a button is clicked, and then slide back to its original position when the same button is clicked again. Although I have been using the toggle method, it doesn't seem to be working for me. I ...

Arrangement of images in an array

Here's the scenario I'm facing. https://i.stack.imgur.com/FbAfw.jpg So, I have an array of images that I want to use to create a gallery with a specific layout. I've tried using grid and playing around with :nth-child(even) and :nth-child( ...

Jumping transitions in thumbnail images

Could you please visit I've noticed that when hovering over the thumbnails in the last column, the images jump a bit after transition, especially in Firefox. Do you have any suggestions on how to resolve this issue? ...

How do you determine the dimensions of a background image?

My div is a perfect square, measuring 200 pixels by 200 pixels. The background image I've chosen to use is larger at 500 pixels by 500 pixels. I'm searching for a method to ensure that the entire background image fits neatly within the confines ...

Establishing the null values for input parameters

Whenever the button is clicked, I want to reset the input values to null. The function spremi() gets triggered when the button is clicked, but I want to set the values of podaci.tezina and podaci.mamac back to their initial values so that the user can en ...

The Intl.NumberFormat function does not support conversion to the pt-BR (Brazilian Portuguese) locale

A code sample is provided below: const formCurrency = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 }) Assuming the input is: var money = 1000.50 formCurrency.fo ...