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

Acquire the input value of a form field prior to its submission

In my Django form, I have a field called monitoring_method that is using an autocomplete-light widget. This widget filters the results based on what the user enters in another field called database_type. My question is: Is there any way to access the value ...

Learn how to verify the existence of a URL or webpage using AJAX or jQuery

When a user is creating a profile, they have the option to include links to their websites or blogs that will be displayed on their profile page. Before saving these links to the database, I would like to verify if the provided URL exists. Is there a meth ...

Placing content retrieved from a MySQL database within a form displayed in a ColorBox

Having difficulty inserting text from a MySQL database into a form (textfield) inside a ColorBox. The current script is as follows: <a href="#" class="bttn sgreen quote1">Quote</a> var postQuote[<?php echo 4id; ?>]=<?php echo $f ...

Conceal navigation button within react-material-ui-carousel

After successfully incorporating the React Material UI carousel, I found it to be quite simple. However, one thing that eluded me was how to hide the buttons and only display them on hover. I tried setting the props navButtonsAlwaysVisible to false, but it ...

Obtaining JSON values by key name using JQuery

I am trying to extract JSON data using an HTML attribute How can I retrieve JSON values based on the translate attribute and "ed" key? JSON FILE { "open" : [ { "en": "Open", "ed": "Opened ...

arranging texts in a vertical stack with wrapping

Looking to change the orientation of my horizontally wrapped list items from vertical to horizontal. Take a look at my code snippet: HTML <ul> <li>Long text goes here.</li> <li>Another Longer Text Goes Here</li> < ...

Check for existing data and update it if found, otherwise insert new data in WordPress

In my WordPress project, I am trying to handle the insertion of a row only if it does not already exist. If the row exists for the current user, I want to update it with a new value. However, when I try to run the code below on an ajax call, it returns no ...

The mobile navigation panel fails to open

I have a menu that I would like to toggle hide/show by adjusting its top position. Before logging in, the menu is structured as follows: <div class="lc"> <h1><a href="./"><img src="logo.png" /></a></h1> <a h ...

"Sending image data in base64 format to a server: A step-by

Instead of directly selecting an image, I decided to dynamically display it using base64 encoding. <img style="width: 412px;" src="data:image/gif;base64,R0lGODlhwAAAAXAAACH5BAEAAPwALA Is there a way to send this image to a server without triggering a ...

Sencha Touch sends a beacon to jQuery

I am looking to incorporate a jQuery plugin into my Sencha Touch application. The challenge is making sure that the jQuery plugin is only initialized after Sencha Touch has finished populating the DOM structure. This is necessary because the plugin needs ...

Having trouble getting jQuery .click to trigger on a dynamically loaded button?

I'm having some trouble with my code. I have a list that loads dynamically with a button inside, and although I have set up jQuery to handle the click event, nothing is happening. Here's a snippet of the code: HTML: <ul id="cart"> ...

Retrieve the row index in PHP after loading data onto a web page

I have been utilizing PHP to retrieve data from a MySQL database and showcase it within a DIV on a webpage. The information I am retrieving pertains to a list of tasks, and I would like users to have the ability to delete a task once it has been completed. ...

Connecting your HTML file to a CSS stylesheet

I'm struggling to connect my "index.html" file with my "stylesheet.css" file. I've tried copying the code from resources like CodeAcademy and w3schools, but nothing seems to be working. I'm currently using Notepad++ as my text editor - could ...

Animating changes on a webpage using CSS transitions in conjunction with the

Can the border color of a simple line div be changed from top to bottom using GreenSock? .line { position: relative; border: 1px solid #c3ced8; width: 0; height: 50px; display: block; content: ''; z-index: 1; top: -19px; marg ...

Incorporate attributes into object properties in a dynamic manner

Currently, I am experimenting with bootstrap-multiselect and my goal is to incorporate data attributes into the dataprovider method. Existing Data Structure: var options = [ {label: 'Option 1', title: 'Option 1', value: ' ...

Getting the JavaScript file name within another JavaScript file - a simple guide

Imagine having an HTML file that references two external JavaScript files. One of these JavaScript files contains errors (likely compilation errors), while the other file includes an onerror method without any issues. When you open the HTML file in a brows ...

Can you explain the concept of "cascading" within CSS?

Can someone kindly explain the specific definition of "Cascading" in Cascading Style Sheets (CSS)? I have heard conflicting perspectives on this topic, so I am seeking clarification here. Any examples to illustrate would be greatly appreciated. ...

Issue with $.ajax request even when valid JSON data is provided

Below is the code I am currently using: var jsonURL = "http://www.sodexo.fi/ruokalistat/output/daily_json/440/2013/10/25/fi"; var request = $.ajax({ url: jsonURL, dataType: "json", type: "GET" }); request.done(functio ...

Heroku: Showcasing a unique page during the application's startup process

Would it be feasible to showcase a static HTML page while the dyno is starting up, just like how a custom page can be shown during errors or maintenance mode? The size of my app's slug is quite significant, leading to a startup time of almost 50 seco ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...