How can you ensure a div stays at the top or bottom of a page based on the user's scrolling behavior?

Hello there! While I know there have been many questions regarding sticking a div to the top or bottom while scrolling, my particular issue is a bit more specific.

My dilemma is that I am looking for the div to stick either to the top or the bottom based on the user's scrolling direction.

To demonstrate the layout of the content, I have created this jsFiddle snippet: https://jsfiddle.net/DTcHh/6155/.

The desired outcome involves having the side content scroll simultaneously with the main content as the user scrolls. Once the end of the side content (top or bottom) is reached, it should then stick in place accordingly.

For instance, using the provided snippet, I aim for the side content to scroll down until "Fixed content Last." becomes visible, and then adhere to the bottom while the user continues scrolling downwards. If the user scrolls back up, the side content should mirror this movement by scrolling up until "Fixed content First." reappears, at which point it should affix itself to the top position.

This is how the HTML structure of the side content appears:

<nav >
      <div id="filterAnchor"></div>
      <div id="filterScroll" class="fixed_div">
          Fixed content First.</br>
          Fixed content.</br>
          Fixed content.</br>
          ...
          [more "Fixed content."]
          ...
          Fixed content.</br>
          Fixed content.</br>
          Fixed content Last.</br>
      </div>
</nav>

Answer №1

Understanding the direction of scrolling is crucial in ensuring that the sticky sidebar remains visible as the content moves. I have made some modifications to this fiddle to achieve this effect.

While there may be room for optimization, the concept should be clear. One challenge lies in detecting when the bottom is reached, and the approach outlined below may not be definitive:

if ($window.height() <= $filterClass.height() + top) {
    $filterClass.addClass('stick-bottom');
    $filterClass.css('top', '');
}

Edit (refer to comments for additional context):

In the revised fiddle, I have introduced support for various scenarios:

1. When the sidebar exceeds the main content's length:
The default position is set to absolute, requiring no JavaScript intervention for proper functionality.

2. When the sidebar surpasses the window height:
The positioning shifts to fixed. As you scroll down (content moves up), the sidebar sticks to the bottom upon reaching it:

// 'top' denotes the top position of the fixed sidebar
if(top < 0 && fixedHeight + top < windowHeight) {
    $filterClass.addClass('stick-bottom');
    $filterClass.css('top', '');
} else {
    $filterClass.css('top', top+diff);
}

3. When the sidebar is shorter than the window height:
Here, the positioning switches to fixed, mirroring the scenario described in the original response above.

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 Jquery to continuously animate elements breaks and repeats the process

I am currently using a jQuery function to animate my text. The issue is that it animates all elements simultaneously instead of separately. I would like each element (h2, h3, and span) to be animated individually. Any suggestions on how I can achieve this ...

Make changes to the HTML file by directly using Jquery or JavaScript

Allow me to elaborate on my current objective. I have an HTML file that requires direct content updates. Specifically, I am working with elements sharing the 'id=test'. My goal is to dynamically update all elements with unique IDs such as ' ...

Utilizing AJAX to dynamically load file references and embed iframes

Is the use of multiple iframes on a website impacting its loading speed? Also, regarding AJAX, let's say I have two JSP pages. The first one contains an AJAX call to the second JSP page. Both pages have JavaScript functions with the same name, let&apo ...

Three Divisions Positioned at the Top, Middle, and Bottom

I need to place 3 divs at the top, middle, and bottom positions. To achieve this, I have used jQuery to calculate the viewport height and apply a percentage of it to the top and bottom divs. However, resizing the page causes issues as the middle div overl ...

Guide to sending a post request with parameters in nuxt.js

I am trying to fetch data using the fetch method in Nuxt/Axios to send a post request and retrieve specific category information: async fetch() { const res = await this.$axios.post( `https://example.com/art-admin/public/api/get_single_cat_data_an ...

Struggling with incorporating a web link into a structured data table

I am currently working on a Django application that utilizes jQuery DataTables to display a list view of items. My goal is to include a hyperlink in the first element of the table, which represents the primary key for the model being displayed. This link s ...

Is this an effective and appropriate method for establishing media queries?

<link id ="style" rel="stylesheet" type="text/css" title="other" href="regularStyles.css" /> <link rel="stylesheet" media= "all and (mid-width: 767px) and (max-width:2049px) and (min-height:767px) and (max-height: 1538px)" href="notePads.css" /& ...

Displaying individual attributes of objects through v-for loop

I have created a table-making component to streamline the process of creating multiple tables. Each table consists of three key elements: The object (an array of objects with one row per object) Headers specific to each table The object properties that n ...

Attempting to extract information from a webpage that contains multiple data tables, but encountering an issue where only the first table is successfully scraped

For my current project, I am attempting to extract data from basketball players' profiles on Basketball-Reference. Each player page on B-R contains several tables of valuable information that I need to access. However, when trying to extract the table ...

Creating a personalized scrollbar for the body using Bootstrap 3

I've been searching for the best solution to customize the scroll-bar in Bootstrap, but I haven't found anything that works perfectly yet. I want to replace the default browser scroll-bar on the body and other elements like panels, wells, and tex ...

Guide on implementing Observables in Angular 2+ to update a single entry in a table in real-time

I'm facing a challenge with my Angular4 and Node.js application. I have a table that displays data with 7 columns using *ngFor. The issue arises when I need to update the last column dynamically and in real-time. Specifically, I want to show a green c ...

Implementing ExpressJS with MongoDB on a MERN Development Stack

After configuring my ExpressJS & MongoDB client and running Nodemon, I consistently encounter the following warning: "DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the ...

Validate forms using jQuery with hidden fields

I have implemented a validator in my project from this URL: . However, I am facing challenges while using it with Chosen ( ), which replaces the default "select" tag with divs and hides the select tag. This issue is similar to the one explained here: h ...

Struggling to retrieve data from AJAX POST request [Revised Post]

I am encountering an issue with posting a form using the AJAX POST method in jQuery. I am using the serialize method to retrieve the form data, but it seems to fail. The problem might be related to the JavaScript files of the Steps Wizard plugin that I am ...

"Create a table from a multidimensional array and showcase it using jQuery: A step-by-step guide

I have successfully returned a multidimensional array from a PHP script to an HTML page via AJAX. The values are correctly returned in the array, confirmed by checking the console.log. Now my question is, how can I treat each array as an individual array ...

Solving the problem of endless looping in JavaScript tree structures

i have been trying to create a tree structure in JavaScript. However, when I use the add_child function to add a child to an item in the elements array, it adds the child to all items in the elements array and their children, creating an infinite loop. I ...

Incorrect sorting of tables in Bootstrap

I've been struggling to position 3 tables as shown in the image, but they keep stacking vertically instead of horizontally. The desired layout is to have two tables on one side and three on the other side. Can anyone provide guidance on achieving this ...

Changing icons using JQuery when clicking 'show more' or 'show less' buttons

I am currently utilizing https://github.com/jasonujmaalvis/show-more to display and hide text content on a mobile device. My goal is to switch between images for show more and show less: Here's what I have so far: Jquery: Source File: ; (function ...

Align the subtext to the right and center it vertically within a Bootstrap dropdown menu item

Is there a way to vertically align small captions on the right side of a dropdown menu, next to each item's text? The issue is that in the example below, the numbers are not properly aligned. https://i.stack.imgur.com/NZigW.png The numbers 123 and 1 ...

Having trouble retrieving image files from CSS within a Spring MVC Application

I am facing an issue with my Spring MVC application where I cannot get an image to display in a CSS file accessed from a JSP file. The CSS is working fine, but the image just won't show up. It seems like there might be an issue with how I am addressin ...