Once you have successfully navigated past Div2, smoothly transition downwards to Div1 and transform it into a sticky

I wish to scroll down, and view #div1... also see #div2... When #div2 disappears from sight, I want #div1 to slide down and stay fixed at the top of the window. If I reach the footer div, I no longer want #div1 to remain sticky.

If it's possible for this effect to work in reverse (scrolling up the page), that would be ideal. There are no set heights involved. Is there a way to achieve this with jQuery?

Click here for a live example on jsFiddle

$(document).scroll(function() {
              var y = $(this).scrollTop();
              var div3 = $('#div3').offset().top;
              if (y > div3) {
                $('#div1').addClass('sticky');
              } else {
                $('#div1').removeClass('sticky');
              }
             });
            

Answer №1

If you don't mind a bit of messiness, I believe this solution could be suitable for your needs:

Live Demo

$(function () {
    $('#test2').height($('#test1').height());
    $(document).scroll(function () {
        //stick nav to top of page
        var y = $(this).scrollTop(),
            div3 = $('#div3').offset().top,
            foot = $('#footer').offset().top,
            div1Height = $('#div1').height() + 10;
        if (y > div3 && y < foot - div1Height) {
            $('#div1').addClass('sticky slider').removeClass('bottom');

        } else if (y > foot - div1Height) {
            $('#div1').addClass('bottom').removeClass('sticky');
        } else {
            $('#div1').removeClass('sticky bottom slider');

        }
    });
});

#test1 {
    margin-right: 300px;
    background: #00ff00;
}
#test2 {
    position: relative;
    width: 300px;
    float: right;
    background: #9FF;
}
#div1 {
    margin: 10px 0 0 0;
    background: #ff00ff;
    border: 2px solid #000;
}
#div2 {
    margin: 10px 0 0 0;
    background: #FF6;
    border: 2px solid #000;
}
#div3 {
    height: 1px;
}
.sticky {
    position: fixed;
    top: 0;
    z-index: 999;
    transition: all .3s;
    -webkit-box-shadow: 0 8px 5px -6px #ccc;
    -moz-box-shadow: 0 8px 5px -6px #ccc;
    box-shadow: 0 8px 5px -6px #ccc;
}
.slider {
    animation: slider .5s; /* Don't forget the use of prefixes for chrome */
}
@keyframes slider {
    from {
        top: -100px;
    }
    to {
        top: 0px;
    }
}
.bottom {
    position: absolute;
    bottom:0;
}

Related resources:

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

What if the v-on:click event is applied to the wrong element?

I'm attempting to manipulate the anchor tag with jQuery by changing its color when clicked, but I'm struggling to correctly target it. <a v-on:click="action($event)"> <span>entry 1</span> <span>entry 2</span> ...

Send a property parameter to the Vue component

In my project using Vue and Laravel, I am trying to create a modal window with 2 tabs. The idea is to have two buttons, with each button linked to a specific tab that should open when clicked. These buttons are located in the blade template: <button ...

How can I keep dragging objects on Raphael JS Freetransform without showing the handles?

Hey there! Currently, I am immersed in a new project that hinges on the utilization of Raphael JS alongside the Raphael.Freetransform plugin. The plugin has been performing admirably with smooth transitions so far. Nonetheless, upon utilizing the hideHandl ...

Neglecting the error message for type assignment in the Typescript compiler

Presented here is a scenario I am facing: const customer = new Customer(); let customerViewModel = new CustomerLayoutViewModel(); customerViewModel = customer; Despite both Customer and CustomerLayoutViewModel being identical at the moment, there is no ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

Is it possible for me to utilize window.top within the .js file?

Within my GWT code, I am transferring a variable to a JSP file. The process looks like this: <html> <head> <script type="text/javascript"> alert("Inside the JSP file"); var criticalPath = window.top.criticalPath; ...

Efficient PHP caching solution for optimizing JavaScript and CSS performance

I'm facing a unique challenge that I can't seem to solve through typical Google searches. I'm in the process of consolidating all my javascript and css into separate php files using require_once() to pull in the content. The structure of my ...

When using the parseFloat function with a regular expression input, it results

My goal is to adjust float values within a string by a specific amount. Here is my current approach: var string = '<path d="M219.6,-71.4C249,19.1,212.7,130.9,135.7,186.8C58.8,242.7,-58.8,242.7,-135.7,186.8C-212.7,130.9,-249,19.1,-219.6,-71.4C-19 ...

Manage multiple sessions at the same time

In a specific scenario, we face the need to manage multiple sessions similar to Google Accounts. Users should be able to add different accounts in separate tabs, each with its own unique content. For example, user1 may be logged in on Tab1 while user2 is l ...

ERROR : The value was modified after it had already been checked for changes

Encountering an issue with [height] on the main component and seeking a solution Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '753'. Current value: '731'. I have th ...

retrieving data from a node and embedding it into an HTML file

In my project, I have an index.html file and an app.js nodejs file. Within the app.js file, there is a variable named "name" that I would like to display in my index.html page. Here is the code snippet: var name = "Utsav"; var HTTP = require('HTTP&a ...

Exploring the world of using Bootstrap containers, rows, and columns

I have a good grasp on containers and columns, but I am a bit confused about rows. The example below shows a 50/50 split. <div class="container"> <div class="row"> <div class="col-md-6"> 50 / 50 Content </ ...

Navigating with Buttons using React Router

Header: I need help figuring out how to properly redirect to a new page when clicking on a Material UI button using the onClick method. Specifically, I am unsure of what to include in my handleClickSignIn function. Here is a snippet of code from my Header ...

"Exploring the versatility of NextJS with dynamic route parameters

Can NextJS be configured to handle dynamic routes that match both /country and /country/city, while excluding matches like /country/city/whatever_content_here? The goal is to display the same content for either of the specified routes, regardless of whethe ...

How can I use AngularJS to save selected assets?

<div style="z-index: 1; position: absolute"ng-show="ctrl.company.selected"> <div style="" ng-repeat="Asset in ctrl.company.selected.Assets"> <div class="pd-5"style="width: 300px; background-color: white; border-bottom: gray solid ...

Streaming live audio through socket io. Need help troubleshooting ALSA shutdown issue

Looking to develop a live audio streaming service using socket.io and ionic 4. On the client side, utilizing cordova-plugin-audioinput and ng-socket-io for Angular. For the server, employing standard npm packages. Node version: 10.16.0 ...

By employing jQuery ajax and leaving out a value for the form action attribute

Recently, I designed an ajax sign-up form using jQuery that connects to a PHP backend. One question I have is whether it's wise to keep the form attribute action="" empty and let the ajax interface handle everything. Are there any potential downsides ...

Showcasing an image stored in an HTML file on a Vue.js webpage

I'm currently facing an issue with displaying a local image saved in an HTML file on my Vue.js page. I attempted to store the content of the HTML file into a variable using the code below: computed: { compiledHtml: function() { return this.a ...

Unable to eliminate the unwanted space at the top of the division

I am encountering an issue where I have a div containing a label, but there seems to be some unwanted space above the div that I can't seem to remove. It's puzzling me as to why this space is appearing. Query: What could be causing the space ab ...

Troubleshooting: React CSS Transition Fails to Trigger on Exit and Entry

This code is located inside my component file <CSSTransition classNames="method" in={radio === 'add-card'} exit={radio !== 'add-card'} timeout={500} unmountOnExit> < ...