Using jQuery to make an element follow you as you scroll down a page inside a div

I've made some progress on my code:

HTML

<div id="header"></div>
<div id="content">
    <div class="sidebar-wrapper"></div>
</div>
<div class="session-wrapper"></div>
<div id="footer"></div>

CSS

#header {
  height: 600px;
  width: 100%;
  background: black;
}
#content {
  height: 2000px;
  width: 100%;
  background: #eeeeee;
}

.sidebar-wrapper {
    width: 350px;
    height: 350px; /*depends on content*/
    background: rgba(0,0,0,0.2);
    border-radius: 20px;
    padding: 20px;
    margin-top: 50px;
}

.session-wrapper {
  height: 200px;
  width: 100%;
  background: #000000;
}

#footer {
  width: 100%;
  height: 500px;
  background: #888;
}

jQuery

jQuery(window).scroll(function(e){ 

var sidebar = jQuery('.sidebar-wrapper');
var sessions = jQuery('.session-wrapper');

var scrollTop     = jQuery(window).scrollTop(),
    elementOffset = sidebar.offset().top,
    distance      = (elementOffset - scrollTop),
    sessionOffset = sessions.offset().top;

var isPositionFixed = (sidebar.css('position') == 'fixed');

    if(distance < 60 && (sessionOffset - elementOffset) > 800 && !isPositionFixed) { 
            sidebar.css({'position': 'fixed', 'top': '100px', 'width': '350px'}); 
    }
    if((sessionOffset - elementOffset) < 800 && isPositionFixed || scrollTop > 1900) {
            sidebar.css({'position': 'static', 'top': '0px', 'width': '100%'}); 
    }

});

SEE JSFIDDLE

To clarify, I am working on a solution where the grey box (sidebar-wrapper) sticks to a certain position while scrolling down the page until it's close to .sessions-wrapper, then it should hold that position until scrolling back up resumes. I believe I'm close to achieving this effect but may need some guidance...

Appreciate any help provided!

Answer №1

There are several techniques you can use to achieve this effect. One way is to utilize the new position:sticky property as shown below:

#sidebar-wrapper{
    position: -webkit-sticky;
    position: -moz-sticky;
    position: -o-sticky;
    position: -ms-sticky;
    position: sticky;
    bottom: 0px;
    line-height: 30px;
    background: gray;
}

You can view an example here: http://jsfiddle.net/4hznD/

If you're looking for a similar solution, you may find this example helpful: http://jsfiddle.net/FDv2J/4/ (taken from: jQuery scrolling DIV: stop scrolling when DIV reaches footer)

You can adapt and use a code snippet like the one below:

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

    var $el = $('#sidebar>div');
    var $window = $(window);

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

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

I hope this information proves useful!

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

Using a jQuery dialog to launch a popup window specifically optimized for Safari browsers

I recently encountered an issue with my plain JavaScript function that opens a pop-up window. It functions perfectly in Chrome and Firefox, but I faced difficulty in Safari due to the default popup blocker preventing the page from opening without any err ...

The enigma of CSS: How is the width mysteriously set to 0px with no visible CSS styling

Take a look at this snapshot of a webpage I'm currently designing in Chrome Developer Tools: https://i.sstatic.net/SB00j.png The primary rule in the 'Matched CSS Rules' section indicates that the width of the element should be 160px. Howe ...

Seamless blend of images with a stunning mosaic transition effect

I attempted to create a mosaic effect on my carousel similar to this example: , but not exactly like this. I want to include control buttons for next and previous, and have images in HTML tag. However, my attempt is not working and I need help. This is ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

Choose individual radio buttons in each group where no checkboxes are already selected

I'm looking to: retrieve all radio button groups that have no option selected within those groups, extract the inputs with "data-correctanswer" attribute Is there a more efficient way to accomplish this task than my current method? (although it&apo ...

Efficiently showcase connected pages in real-time

I've come across an issue with my express app. Whenever a navigation link (such as Home, Home1, or Home2) is clicked, an error occurs. However, if I manually type in http://localhost:8001/home1, it displays home1.html without any issues. What I' ...

Create a feature that allows for the dynamic alteration of the ID for a checkbox in a Rails application, enabling each checkbox

I'm running into issues with generating unique IDs for each product in a loop within my Rails variables. I need every "product" to have its own individual ID on the switch element so that I can toggle the switch when an item from the dropdown is selec ...

Remove a div element from a slider without permanently deleting or removing the div element from the DOM

Is there a way to dynamically remove slides from a slider (created with iscroll) while also being able to refresh the slider to restore all the original slides? What is the best approach for achieving this? This is how the HTML is structured: <div id ...

What is the best way to adjust the layout of these two elements using CSS in order to display them on

I need assistance with adjusting the layout of a dropdown list next to its label in an Angular html page. <div *ngIf="this.userRole == 'myrequests'" class="col-2" [ngClass]="{ 'd-none': view != 'list&apo ...

What is causing gog.com to malfunction when accessed through chromedriver?

Can you figure out why the appearance of gog.com differs between Google Chrome (left) and Chromedriver (right)? It's noticeable that things appear distorted and broken in Chromedriver. Even after comparing the two HTML codes, no significant differenc ...

Looking for a replacement for EO.Pdf to convert HTML to PDF in C#? Check out wkhtmltopdf!

Currently, I am in the process of creating an HTML catalog for movies, with plans to convert it into a PDF format. While using EO.Pdf initially showed promise with a small test sample, issues arose when attempting to run it against the entire list of movie ...

Notify customer upon database update

I'm working on developing a messaging system in asp.net. How can I notify the client when there is a change in the database? For instance, if a user's page is open and another user sends them a message, how can the software alert the user? Is it ...

Utilizing the Jackson Framework in Spring Boot for effective mapping with @RequestBody annotation

Hello everyone. I am dealing with some data fetched from a jQuery DataTable and sent to a Spring Controller using Ajax. The ajax function snippet looks like this: $.ajax({ url: "../todaydatarecover.json", t ...

Generate a new array of objects by cloning an existing array of objects with placeholder values

I am looking to transform an array of objects into another array of objects in order to generate a graph. Below is the array I am using to determine the position of each object within the new object. let uniqueSkills = ['Using', 'Analyzing ...

Looking to display dropdown menus on a new line along with a text input field using jQuery?

<script type="text/javascript"> var arr = [{ val: 1, text: 'Option 1' }, { val: 2, text: 'Option 2' }]; $(function () { $('a').click(function () { var sel = $('<select>&apo ...

Tips for implementing validation in AngularJS

Could someone help me with AngularJS validation? I'm new to it and trying to make sure everything is correct. var app=angular.module('myApp',[]) app.controller('myController',function($scope){ $scope.clickMe = function(){ if($(& ...

When is the appropriate time to nest CSS class selectors within other class selector definitions?

REVISED 1 After receiving feedback, I made the following changes: .lower-container { justify-content: center; position: absolute; width: 92vw; // height: 46vh; <--- no set height /* nested classes for adjusting position and height of low ...

Adjust header display for smaller screens

Looking for help with adjusting my header design on small screens: I want the search bar to go underneath on smaller screens, like this example: I've tried changing the position to relative at a certain screen width but it didn't work. <di ...

Incorporating jQuery into Rails 6.1

I encountered some difficulties while setting up jQuery in rails 6.1, even though I believe it's configured correctly. Below are the steps I've taken: Installed yarn add jquery 2. In config/webpack/environments.js, I made the following changes ...

Fade in and out of div elements upon clicking on an # anchor

I have been attempting to create a function where different divs fade in and out when clicking on an image with an <a href>. Unfortunately, I have not been successful in getting it to work despite several attempts. Here is the code that I am using: ...