Prevent fixed element from scrolling beyond a specific point

I'm working on a fixed sidebar that needs to scroll along with the main content and stop at a specific point when scrolling down, and vice versa when scrolling up.

I've created a script that calculates the window height, current scroll position (scrollY), and the point where the sidebar should 'stop'. I control the stopping point by adjusting the css 'bottom' property. However, I am encountering two issues with this method:

  1. When the sidebar is close to the 'pagination' where it should stop, it suddenly jumps down as I scroll up, and vice versa.
  2. As I scroll the page, the sidebar moves continuously instead of staying in place

Below is the code I am using. HTML:

<div class="container">
  <aside></aside>
  <div class="content">
    <div class="pagination"></div>
  </div>
  <footer></footer>
</div>

CSS:

aside {
  display: flex;
  position: fixed;
  background-color: #fff;
  border-radius: 4px;
  transition: 0s;
  transition: margin .2s, bottom .05s;
  background: orange;
  height: 350px;
  width: 200px;
}

.content {
  display: flex;
  align-items: flex-end;
  height: 1000px;
  width: 100%;
  background: green;
}

.pagination {
  height: 100px;
  width: 100%;
  background: blue;
}

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

JS:

let board = $('.pagination')[0].offsetTop;
let filterPanel = $('aside');
    if (board <= window.innerHeight) {
        filterPanel.css('position', 'static');
        filterPanel.css('padding-right', '0');
    }

$(document).on('scroll', function () {
    let filterPanelBottom = filterPanel.offset().top + filterPanel.outerHeight(true);
    let bottomDiff = board - filterPanelBottom;

    if(filterPanel.css('position') != 'static') {

        if (window.scrollY + window.innerHeight - (bottomDiff*2.6) >= board)
            filterPanel.css('bottom', window.scrollY + window.innerHeight - board);
        else
            filterPanel.css('bottom', '');
    }
});

Check out the live demo on Codepen here

The sidebar is denoted by an orange background, while the block indicating its stopping point is highlighted in blue. Thank you in advance for any assistance provided.

Answer №1

After encountering an issue, I found a helpful solution detailed here

let window = this;
let paginationOffset = $('.pagination').offset().top;
let asideHeight = $('aside').outerHeight(true);
let coords = paginationOffset - asideHeight;
console.log(coords)
$.fn.followTo = function ( position ) {
    var $this = this,
        $window = $(window);
        
    $window.scroll(function(event){
      
        if ($window.scrollTop() > position) {
            $this.css({
                position: 'absolute',
                top: position
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('aside').followTo(coords);

I also determined the coordinates by calculating the endpoint offset top minus the sidebar height. To view the implemented solution, visit my codepen page

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

Having trouble getting @media queries to work effectively across various screen sizes

Currently, I am using Sass with Bootstrap and facing some challenges when implementing different media queries. Despite most discussions revolving around CSS problems only, I am uncertain of the source of my issue and how to effectively address it. The sty ...

Using jQuery to smoothly animate a sliding box horizontally

Is there a way to smoothly slide a div left and right using jQuery animation? I have been trying to achieve this by implementing the code below, which can be found in this fiddle. The issue I am facing is that every time I click on the left or right butto ...

Ways to initiate animation using CSS when the page loads

Is there a way to initialize the counter on page load? Even though I was successful in making it start on hover, I couldn't figure out how to make it work when the page loads. Here is the JavaScript code: var root = document.querySelector(':root ...

Is there a way to leverage the useSWR hook for making numerous requests simultaneously?

I am attempting to utilize the useSWR hook for multiple calls, but I keep encountering an error message that reads: Cannot read properties of null (reading 'destroy') async function FetchApi(url) { const response = await fetch(url); const ...

Don't forget to keep track of when the user has closed

How can I ensure that the cache retains the user's action of closing the div? Currently, when I close the div and refresh the page, it reverts back to its original state. Is there a way to make this change persistent? Experience it live: Here is the ...

Stop the div from expanding because of oversize text in Bootstrap

I have the following HTML source code for a Bootstrap card: <div class="card shadow-none card-fluid mb-3 mb-md-5"> <div class="row"> <div class="col-md-3 col-lg-3 mb-3 mb-sm-0"> <img class="img-fluid rounded" ...

What is the best way to implement filter functionality for individual columns in an Angular material table using ngFor?

I am using ngFor to populate my column names and corresponding data in Angular. How can I implement a separate filter row for each column in an Angular Material table? This filter row should appear below the header row, which displays the different column ...

What is the best way to apply styling exclusively to a child component?

I am currently working on a coding project that involves a parent component and multiple child components. My main goal is to adjust the position of a filter icon by moving it down 5 pixels on one specific child component. The issue I am facing is that no ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Testing the capabilities of AngularJS with e2e testing using the angular-recaptcha library

I have been attempting to e2e test my basic application, but I am facing challenges with the angular-recaptcha plugin from VividCortex (https://github.com/VividCortex/angular-recaptcha). Here is the test case I am working on: it('should redirect t ...

The slider's border-radius is not being maintained as it moves from left to right

We recently implemented a slider on our website, located at . While we added a border-radius to the slider, we noticed that when the images slide, the border-radius is slightly removed... I attempted to contain the parent element with overflow: hidden, bu ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

Can WebDriver (HtmlUnit, Ruby bindings) be configured to bypass JavaScript exceptions?

When attempting to load the page, HtmlUnit throws an exception and crashes my test. caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true) driver = Selenium::WebDriver.for(:remote, :desired_capabilities => caps) drive ...

What are the advantages of using React JS for a Single Page Application compared to server-side rendering?

Currently, I am faced with a conundrum when it comes to selecting the best approach for a highly scalable project. On one hand, server-side rendering using Node.js with Express (utilizing EJS) to render full HTML pages is an option. On the other hand, ther ...

Utilizing a variety of Zend pagination controls through AJAX and jQuery technology

Looking for assistance in implementing multiple Zend pagination in a view using AJAX. Single pagination is already working, but now the goal is to have more than one. This is the current setup:- Added to the bootstrap:- public function _initPaginator(){ ...

What is the best way to position the logo in the center of the navigation bar, considering there are an unequal number of menu items on each side

As I work on coding a design I found for practice, I am facing the challenge of getting the logo to be centered in the navbar, similar to the layout in the Dribble link below. View Design on Dribble The navigation bar has 4 items aligned on the left and ...

After successfully sending a GET request to the API, the Next.js 13.4.3 website still does not reflect new posts added on the hosting platform

I am currently using Next.js version 13.4.3 in my app directory to create a blog site. However, I am facing an issue. When I run npm run build locally on my computer and then start with npm run start, the new posts are displayed normally after adding them ...

Can Facebox's settings be adjusted during runtime? If so, how can this be done?

Can Facebox settings be accessed and customized? For instance, I am interested in setting the location of the loading image dynamically as shown on line 4: <script type="text/javascript" src="<?php echo base_url(); ?>media/facebox/facebox.js" > ...

Looking for assistance in establishing a connection between Node.js and Angular.js

I have a decent understanding of mongodb and node.js, but I'm struggling with angular.js. I need some help in figuring out how to retrieve data from my node.js code using angular.js. If there are any errors in my node.js code, please let me know. var ...

What is the best way to modify the size of the letter background?

I'm facing an issue with a word that has a background color. While using the CSS property background-color: blue, allows me to give the word a background color and display: inline-block helps in sizing it exactly to the word, the problem arises when I ...