Why isn't the sticky element moving up along with its sibling element when scrolling?

This is an additional query related to my previous question

How can I make an element sticky but scrollable to its full (variable) height with a sibling element?

The issue at hand is that the right sidebar does scroll to its full available content and then becomes sticky, allowing the user to scroll the main section to view its content, similar to the behavior on Twitter. However, the problem arises when the user scrolls up; the right sidebar does not scroll up until the user reaches the very top of the page. To gain more insights, try increasing the heights of the columns.

What would be the best way to resolve this issue?

Effective Solution

var lastScrollTop = 0;

document.addEventListener("scroll", function() {
  var st = window.pageYOffset || document.documentElement.scrollTop;
  document.querySelector('.right-sidebar').classList.toggle('scroll_down', st > lastScrollTop);
  lastScrollTop = st <= 0 ? 0 : st;
}, false);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  position: relative;
  display: grid;
  grid-template-columns: 1fr 3fr;
  min-height: 100vh;
  font-size: 2rem;
}

.inner-grid-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.left-sidebar,
.right-sidebar,
.main {
  margin: 0 1rem;
}

.left-sidebar,
.content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.content {
  height: 95%;
  margin-top: 2.5rem;
}

.left-sidebar {
  background-color: burlywood;
  height: 100vh;
  position: sticky;
  top: 0;
}

.main {
  background-color: tomato;
  height: 3000px;
}

.right-sidebar {
  background-color: cadetblue;
  position: sticky;
  min-height: 100vh;
  height: 1000px;
  top: 0;
}

.scroll_down {
  top: unset;
  bottom: 0;
  margin-top: auto;
}

.fixed-header {
  background-color: black;
  color: white;
  position: fixed;
  width: auto;
  top: 0;
}
<div class="container">
  <div class="left-sidebar">
    <div>
      <div>left sidebar</div>
      <div>top</div>
    </div>
    <div>bottom</div>
  </div>
  <div class="inner-grid-container">
    <div class="main">
      <div class="fixed-header">fixed header</div>
      <div class="content">
        <div>
          <div>main</div>
          <div>top</div>
        </div>
        <div>bottom</div>
      </div>
    </div>
    <div class="right-sidebar">
      <div class="fixed-header">fixed header</div>
      <div class="" style="margin-top: 2.5rem;">
        <div>
          <div>right sidebar</div>
          <div>top</div>
        </div>
        <p style="font-size: 1rem;">Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde iste, repudiandae quasi, cumque mollitia animi, libero dolores aliquam ipsam optio veritatis tempore eius. Nemo magni molestiae quis similique itaque dolorem quisquam, neque odit debitis
          earum deleniti ut natus distinctio ipsa repellendus tempore voluptatem cupiditate sunt delectus quo? Pariatur, quis modi natus molestiae quibusdam quod, dolore perferendis deserunt deleniti fugit, fuga voluptas a numquam accusamus quam aliquam?
          Ipsa necessitatibus perspiciatis sunt eaque, incidunt vitae, labore autem, quos voluptatibus numquam commodi earum non iusto. Sapiente quis, praesentium maxime odit, eligendi libero illo necessitatibus deserunt nisi, assumenda culpa ducimus
          cum debitis dolores sequi?</p>
        <img src="https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1" width="150" height="300" alt="">
        <div style="position: absolute; bottom: 0;">bottom</div>
      </div>
    </div>
  </div>
</div>

Answer №1

I created a Twitter-inspired page with a right sidebar feature

Feel free to explore and see if this fits your needs

var lastScrollTop = 0;

document.addEventListener("scroll", function(){ 
   var st = window.pageYOffset || document.documentElement.scrollTop; 
      document.querySelector('.right_parent').classList.toggle('scroll_down',st > lastScrollTop);
   lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);
    .left
    {
        position: sticky;
        top: 0;
        left: 0;
        height: 100%;
    }

    .head
    {
        position: sticky;
        top: 0;
        left: 0;
        background: white;
    }

    .right_parent
    {
        position: sticky;
        height: 100%;
        top: 0 !important;
        margin-top: 0;
    }

    ...

</div>

Answer №2

During my experimentation, I quickly realized that an element with a position: sticky style, when wrapped and the sole element inside the wrapper, fails to stick as expected.

To resolve this issue, it's recommended to isolate the right sidebar completely from other HTML divs, as shown in the following quote:

The reason behind this behavior is that when an element is assigned the position: sticky style, its sticking capability is limited to the container of the sticky item. Without any sibling elements for it to float over, the item loses its sticky functionality since it lacks the necessary elements to interact with.

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

The alert stubbornly refuses to close even when attempting to do so

I am encountering an issue with an alert in my Bootstrap 5 project. The alert does not close when I click on the "X" button. https://i.sstatic.net/pvCdm.png Below is the code snippet: {{#if success}} <div class="container p-4"> ...

Is there a way for my extension to prevent a rickroll from starting before the video even begins?

I'm working on creating a Chrome extension that prevents rick rolls. Here's an overview of my manifest.json file: { "name": "AntiRick", "version": "1.0", "description": "Introduci ...

Converting JSON data into HTML format

I have been tasked with displaying a list of news articles on my webpage, and I have been provided with a link to a json file containing the necessary data. My goal is to convert the information in the json file into HTML format. Here is a preview of the ...

Modify CSS using JavaScript at a specific screen size

Currently, I am in the process of designing a responsive navigation system which involves implementing a button that dynamically changes the styling of the div #navigation using Javascript. The aim is to toggle between display: none; and display: block; ba ...

What is the process for mediating a SWF-Flash file with a PHP mediating, also known as an HTTP-Pseudostreaming script?

I am currently developing a mini context media platform that utilizes HTTP Pseudostreaming. This involves using a PHP script to manage the media file, ensuring proper access and linking to the correct directory. Below are the key components of my code: // ...

Uncovering the Power of Shadow DOM within HTML

Lately, I've noticed a lot of buzz surrounding Shadow DOM. During a video I watched about the launch of Angular 2, the speaker kept mentioning Shadow DOM without much explanation. Can someone clarify what exactly Shadow DOM refers to? ...

Despite utilizing the .img-fluid class, the image remains incompatible with the parent div and does not fit properly

So, I'm currently working on a test code where my aim is to fit an image into the parent div using Bootstrap 5. However, I'm facing a challenge where the image leaves a noticeable gap width-wise, despite using the .img-fluid class. You can see th ...

Determining the dimensions of a div with a scrollbar using Jquery

Is there a way to get the width and height of a div with scroll that includes both visible and hidden content using JQuery? If anyone has a solution for getting these values, please share. <div id="area" class="divLeftCem area"> <div id="pan ...

I'm having trouble getting vite-plugin-fonts to work. It doesn't seem to be doing anything

Hey there! I was trying to bring in a custom font with vite and came across this handy plugin called vite-plugin-fonts. I set it up like this: import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import * as pa ...

How can I align those 3 divs in the center of the body?

Can someone help me with centering those 3 divs in the body? I have tried creating 2 versions of the row, one with an extra outer wrap around the column and one without. Unfortunately, since this HTML was created with a page builder (WP visual composer), I ...

Having trouble making SCSS mixins work with CSS variables in NextJS?

My current next.config.js setup looks like this: module.exports = (phase, {defaultConfig}) => { if ('sassOptions' in defaultConfig) { defaultConfig['sassOptions'] = { includePaths: ['./styles'], ...

I'm looking for a way to incorporate JavaScript code within an iframe tag. Specifically, I'm attempting to embed code into a Wix website using the "Embed HTML

Trying to execute the code below on a Wix website using "Embed HTML", but IFRAME is blocking scripts. Seeking help to embed custom HTML with JavaScript on platforms like Wix.com or Wordpress.com, as the embedded code is not functioning due to IFRAME restri ...

What is the most efficient method for tallying the occurrences of the character "." in a webpage?

I am looking to analyze the content of an html page and tally up the occurrences of "." (period). Below is a snippet of code that accomplishes this task by reading the html and displaying the desired results. While considering modifying the existing code, ...

jQuery User interface smooth scrolling feature

When my jQuery UI dialog is minimized, it moves to a container on the left side. How can I implement a custom jQuery UI scrollbar for that container? I attempted this approach, but only received the default bland scrollbar: #dialog_window_minimized_con ...

What is the best way to duplicate an image on both sides in a vertical manner?

I've successfully implemented a background image on the left side of the website, however, I'm facing difficulty in replicating the same effect on the right side of the webpage. <style> body { background-image: url('background. ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

The div is not positioned on the left side

I'm struggling with aligning three divs next to each other in HTML and CSS. I've set them to float: left, but they are not obeying this style rule. .threethings { width: 20%; } .threethings div { text-align: center; position: relative; ...

The sidebar scrolling feature seems to be malfunctioning, as only the page scrolling functionality is currently

I'm currently working on a webpage that features a sidebar, along with other elements as shown below: https://i.sstatic.net/gf7dX.png In this design, the Your Friends section represents the sidebar. However, I have noticed that when I hover over the ...

Leverage PHP email functionality by incorporating variables within the email

I am utilizing Google to create a QR code using a random number. Once the number is generated, it is saved as a variable. My intention is to incorporate this variable within an image link in an email. Below is an example of how I want to achieve this: Th ...

Stop manipulating links with jquery mobile to maintain original behavior

I have a situation where I am listing WordPress posts, and when I click on a title, jQuery is loading the single post page for me via ajax. However, I don't want this behavior - I just want the link to act normally. I have tried using the following co ...