Element with adhesive properties contained within a div set to absolute positioning while scrolling

I have a div with the CSS properties of position: absolute and overflow: auto. Within this div, there is another div that I want to behave as a sticky element, staying fixed (

top: 0, bottom: 0, overflow: auto
) when scrolling.

I am able to fix this div in place, but facing difficulty returning it to its original position because I cannot attach the scroll event properly while it's fixed.

$('.right').scroll(function() {
    if ($('.scroll').offset().top <= 0) {
        $('.scroll').css({
            'position': 'fixed',
            'top': 0,
            'left': '20px',
            'right': '0',
            'overflow': 'auto'
        })
    }
})

Please refer to my JSFiddle for more details - JSFIDDLE

Thank you.

Answer №1

My approach to achieving the desired effect involves not fixing the position, but maintaining a similar appearance. When the scrollTop value surpasses or equals the designated point where the content should appear fixed, we adjust its top position absolutely in correlation with the current scrollTop value. Upon scrolling upwards and passing the previous fixed position, the content will return to its original state.

$(document).ready(function() {
  oldOffset = $('.scroll').offset().top;
  $('.right').scroll(function() {
    if ($('.right').scrollTop() > oldOffset) {
      $('.scroll').css({
        'position': 'absolute',
        'top': $('.right').scrollTop(),
        'left': '20px',
        'right': '0',
        'overflow': 'auto'
      });
    }
  });
});

(Check out the demo here!)

Answer №2

Make sure the outer div has

position: relative;

Then, for the inner div, set it to

position: absolute;
top: 15px;
right: 15px;

By doing this, you will place the top right corner of the inner div at the specified location within its parent container. Remember that when using position absolute, the element is positioned relative to the nearest ancestor with a defined position value other than default. If there is no such ancestor, the absolute positioning will be based on the viewport.

Answer №3

Trying to achieve this task may seem quite unusual :)

However, here is the issue at hand:

When you apply the position: fixed property to your inner div, it ends up overlapping your div.right and preventing scrolling events from occurring.

To resolve this, you can add pointer-events: none to the div.scroll so that your div.right can continue to listen for scroll events without interference.

Yet, implementing this solution introduces a new challenge - setting your div.scroll to position: fixed causes it to lose its position within the div.right, causing the latter to jump to the top of the scroll automatically. To counteract this, you must create a clone of the div.scroll, initially setting its height to 0 and then changing it to auto when the inner element becomes fixed.

Note: Using pointer-events: none disables all mouse events, including text selection.

Here is the necessary code snippet:

JavaScript

$(document).ready(function() {
    var container = $('.right');
    var scrollElement = $('.scroll');
    var clonedScrollElement = scrollElement.clone().addClass('clone');
    scrollElement.before(clonedScrollElement);
    container.scroll(function() {
        var condition = clonedScrollElement.offset().top <= 0;
        scrollElement.toggleClass('stick', condition);
        clonedScrollElement.toggleClass('stick-clone', condition);
    });
})

CSS

.scroll {
    background: yellow;
    pointer-events: none;
    overflow: hidden; /* Remove top offset from h1*/
}
.scroll.stick {
    position: fixed;
    left: 20px;
    right: 0;
    top: 0;
}
.scroll.clone {
    height: 0;
    overflow: hidden;
}
.scroll.clone.stick-clone {
    height: auto;
}

JSFiddle Link

Answer №4

If you're looking for a solution, consider the following method:

Start by creating a CSS class instead of using inline styles for better organization. This class can be added and removed from the .scroll element as needed.

CSS

.fixed-top {
    position:fixed;
    top:0;
    left:20px;
    right:20px;
}

Next, wrap your .scroll element within another div. This additional wrapper will help in tracking the original height of your .scroll div with JavaScript.

HTML

<div class="scroll-wrapper">
    <div class="scroll"></div>
</div>

Lastly, save the scrollTop value in a variable when applying the fixed position initially. Use this stored value to decide when to remove the fixed styles from the .scroll div. Ensure that the .scroll-wrapper element's height matches the .scroll element for proper scrolling functionality.

Javascript

 var startScrollTop = 0;
    $('.right').scroll(function () {
        var $scroll = $('.scroll');
        if ($scroll.offset().top <= 0 && $('.right').scrollTop() > startScrollTop) {
            if (startScrollTop === 0) {
                startScrollTop = $('.right').scrollTop();
            }
             $('.scroll-wrapper').css("height", $('.scroll').height() + 300);
            $scroll.addClass("fixed-top");
        } else {
            $scroll.removeClass("fixed-top");
        }
    })

Check out this fiddle for a live example. http://jsfiddle.net/a924dcge/25/

Hope this explanation helps!

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

Troubleshooting JavaScript Date Problem with Internet Explorer 7

When I retrieve a Date from a web method, it comes in the format of "Mon Sep 30 07:26:14 EDT 2013". However, when I try to format this date in my JavaScript code like this: var d= SomeDate.format("MM/dd/yyyy hh:mm:ss tt"); //Somedate is coming from the we ...

Using $scope.$on name parameter as an attribute within an AngularJS directive

My goal is to create a directive that allows me to pass in an attribute string, which will then be used as the "name" parameter when subscribing to events using $scope.$on. The process involves: An object is broadcasted using $rootScope.$broadcast, label ...

Is there a way to extract a single value from an array of data and convert it into a series of values separated by commas, all using JavaScript but without

Here is an array data in a specific format: const data= [ { name: "productname", id: "1356", price: "0.00", category: "Health", position: "1", list: "New Products", ...

Querying GraphQL: Retrieving partial string matches

I have set up a connection to a mongoDB collection using graphQL. Here is the data from the DB: { "_id" : ObjectId("59ee1be762494b1df1dfe30c"), "itemId" : 1, "item" : "texture", "__v" : 0 } { "_id" : ObjectId("59ee1bee62494b1df1dfe30d" ...

Instructions for subtracting the value of a cell in column 22 from a cell in column 24 within the same row when a change trigger occurs utilizing Google Apps Script

I need help modifying the script below to only subtract the row on which the change is made, instead of subtracting all rows in the sheet when the on-change trigger executes. var sourceSpreadsheetID = '1r4e4BNKwsmdC2Ry93Mq-N49zj3DAZVpHG21TgTe0FWY&a ...

Unable to refund items in the list box

I have been working on a code snippet to retrieve a list of items from a listbox. The listbox can contain any number of 10-digit numbers in multiple rows. However, when I run the code, the "NPIListBox.Items.Count" function only returns a count of 1, even w ...

Analyzing the elements of an array in JavaScript and making modifications to it based on their values

Looking for a Solution Current Data- id price 1001 200 1001 150 1002 300 1003 50 1002 70 1004 30 Desired Outcome id price 1001 350 1002 370 1003 ...

Learn the steps to extract attributes from a jQuery-selected element effortlessly

for instance <a href="http://stackoverflow.com" class="selected">stackoverflow</a> this is my jquery code snippet alert($('.selected').attr('href')); however, it's not functioning Can anyone provide guidance on how ...

Pull in data using AJAX and store it in an array. [JavaScript]

I'm in the process of working on an AJAX script that loads a file into an array. function loadGame() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { g ...

Struggling to minimize the dimensions of the Image div in React Js with Tailwind CSS

I am currently working on replicating the functionality of the Book My show Application. Specifically, I am developing a Cast and Crew slider. Despite my efforts to decrease the size of the images, the spacing between them remains unchanged. Here is my Ja ...

Adding an overlay to a material UI table row: Step by step guide

My code is rendering a row in the following format: `<TableRow key={row.name} > <TableCell>{row.empId}</TableCell> <TableCell>{row.userId}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{r ...

Guide on Extracting Python/Django Lists and Dictionaries for Use in Javascript

Is there a way to efficiently pass server-side data to JavaScript for display purposes? I have a list of serializable dictionary objects that represent parts of my data model and I want to utilize these in my JavaScript code. Here's how the objects ar ...

Node.js - Error: Undefined:0 SyntaxEncountered an unexpected end of input syntax error

Exploring Node.js and Backbone.js for the first time. Using the book "Backbone Blueprints" but encountering issues with the provided code to set up the webserver. Node.js is installed and running fine. Here's the package.json code: { "name": "simp ...

Organize my JavaScript code by implementing a function

I have repetitive javascript code that I would like to refactor into a function. Is there a way to streamline this process and make the code more efficient? The two functions I want to consolidate are: bright() $(VARIABLE).find('.info').fadeTo ...

The v-model for a particular field is not reflecting real-time updates like the other fields with the same datatype. I'm trying to figure out what could be causing this issue

In my specific model, there are various values that can be updated through a form on the webpage. These values include "Quantity", "Rate", "Amount", "Net rate", and more. The problem I am facing is with binding these values with my inputs using v-model. E ...

Best way to store extensive data tables in ReactJS

My application utilizes Flask as the backend and React as the frontend, processing vast amounts of data consisting of millions of rows. While sending this data from the backend (where it is stored in a Python dataframe) to the frontend in JSON format prov ...

The element is anchored within a div, but its position is dependent on a JavaScript script

I am dealing with a situation where I have a div named "Main_Card" containing text and an icon. When the icon is clicked, it moves the "Main_Card" along with everything inside of it. The challenge arises when I need to set the icon's position as eithe ...

What is the best way to implement dynamic filtering in Nest JS?

I have a unique software application that requires dynamic filtering, but I am facing a challenge with different fields where I cannot specify any field specifically. Can you provide me with some guidance or articles on how to tackle this issue? Here is a ...

Whirlwind web communication blob item

Currently, my code is designed to transmit data from a website to a server, which will then send the message back to the website for display. JQuery is being used for the website and Tornado for the server. While the current code successfully sends text to ...

Warning: The current engine for Server Discovery and Monitoring is no longer supported and will be phased out in

It seems like the problem has been resolved, but in reality, it persists. The current setup includes: Mongoose 5.8.4 and Nodemon 2.0.2 are being utilized. const mongoose = require('mongoose'); const config = require('config'); const ...