Navigating a stationary div within an overflowing container: Key steps

I've been grappling with this issue for quite some time. I'm in need of a div that remains fixed in position when its parent is scrolled horizontally, yet moves along with the content when scrolled vertically. The key is to ensure that the scrolling appears seamless.

You can view an example of the problem on this jsfiddle. The issue arises when the fixed div doesn't disappear from view upon reaching the top border of its parent container.

Although I previously posted a similar inquiry on Stack Overflow, I didn't receive any helpful responses. The jsfiddle linked there provides a clearer illustration of my objective.

I've come across several queries resembling mine, but most are resolved using "sticky" techniques. Many solutions referenced in this article focus on sticky elements, which isn't exactly what I'm looking for.

Your assistance would be greatly appreciated as I'm currently at a standstill :-)

ps: I've encountered examples where the fixed div scrolls beyond the browser window, but not outside a parent container.

EDIT: While I have found solutions for scenarios involving individual scrollbar movements, they fail when dragging diagonally.

Answer №1

I have found the solution you are looking for. I was able to strategically position the green child element (#container2) so that it remains fixed when horizontally scrolling, while maintaining its horizontal offset during vertical scrolling.

Here is the jQuery code:

var $container = $("#container");
var $content1 = $("#content1");
var $content2 = $("#content2");

var content2InitTop = $content2.offset().top;
var content2InitLeft = $content2.offset().left;


$container.on('scroll', function () {
    var scrollTop = $(this).scrollTop();
    var scrollLeft = $(this).scrollLeft();

    if (scrollLeft == 0 && scrollTop == 0) {
        $content2.removeClass('fixed');
        $content2.offset({
            'top': content2InitTop,
            'left': content2InitLeft
        });
    }

    if (scrollLeft > 0) {
        $content2.addClass('fixed');
        $content2.offset({
            'top': content2InitTop - scrollTop
        });
    } 

    if (scrollTop > 0) {
        $content2.removeClass('fixed');
        $content2.offset({
            'top': content2InitTop - scrollTop,
            'left': content2InitLeft
        });
    } else {
        $content2.offset({
            'left': content2InitLeft
        });
    }
});

Additionally, here is the corresponding CSS:

div, body {
    margin : 0px;
    padding : 0px;
    border : 0px;
}
#container {
    width: 400px;
    height: 200px;
    margin: 45px;
    overflow: auto;
    border: 5px solid pink;
}
#inner {
    width: 800px;
    height: 500px;
    position: relative;
}
#content1 {
    width: 300px;
    height: 50px;
    background-color: red;
}
#content2 {
    width: 150px;
    height: 50px;
    background-color: green;
    margin-top: 10px;
    position: absolute;
}
#content2.fixed {
    position: fixed;
    background-color: lightgreen;
}

Lastly, you can view the demonstration on this fiddle: http://jsfiddle.net/audetwebdesign/7Aw6M/

Answer №2

The solution to your question involves using the following CSS property:

position:absolute

It's important to note that a parent element cannot hide overflow for a fixed element.

For further reference, you can visit this link: http://jsfiddle.net/sczpY/7/

Answer №3

Check out the live DEMO http://jsfiddle.net/MPsFC/1/

Everything is functioning perfectly after implementing some additional code.

var $container = $("#container");
var $content1 = $("#content1");
var $content2 = $("#content2");

var content2InitTop = $content2.offset().top;

var lastScrollTop = 0;
$container.on('scroll', function() {
    var scrollTop = $(this).scrollTop();
    var scrollLeft = 0 - $(this).scrollLeft();           

    if (scrollTop <= lastScrollTop) {
        $content2.addClass('fixed');
        $content2.offset({'top': content2InitTop - scrollTop});
    }
    else {
        $content2.removeClass('fixed');
    }           
});

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

What is the best way to set a newly selected HTML option as the first choice?

I'm facing a simple problem in JavaScript that I can't seem to crack. Admittedly, I am new to working with JavaScript. My issue lies with sorting a dropdown list in alphabetical order while also keeping the selected value at the top. Whenever a ...

What are some debugging techniques for troubleshooting jQuery.post() requests when using JSON as the dataType?

Despite my efforts to rely solely on the search function, I am faced with an issue that I can't seem to resolve: Using jQuery, I call a PHP script to fetch values which are then used to update my HTML elements. Here is a snippet of my code: $.post( ...

What is the process of selecting a hyperlink?

Currently working on enhancing the functionality of my script. The main purpose of this script is to download a page using curl in PHP for authorization purposes. Once the page is downloaded, I need to interact with a button labeled "LOGIN" to input my log ...

Creating custom jQuery plugins involves defining prototype functions that can receive callback arguments

My experience with jquery plugins is limited, and I'm struggling to grasp the concept. Recently, I attempted to customize this image cropping plugin by adding a new callback for dynamically setting the aspect ratio. In cropper.js, I included a new fu ...

Struggles with conflicting versions of Jquery within asp.net

Here is a snippet of my jQuery function: $(window).scroll(function () { if ($(window).scrollTop() > offset.top) { $("#sidebar").css("marginTop", $(window).scrollTop.length - offset.top); $("#sidebar").css({ o ...

Tips for reducing the JavaScript file size outputted by a liquid template generator

Currently, I am working on enhancing the performance of my Shopify website and GoogleSpeed Insights is suggesting that I minify css and js files. However, the recommended files are all created by the liquid template generator, making it challenging to uti ...

What is causing the inconsistency and instability in this jQuery sortable configuration?

I have created a page where users can interact with green blocks by dragging and re-ordering them from one sliding area to another. Sometimes, however, the dropping and sorting functionality is unreliable. The boxes may align incorrectly or the drop area m ...

Clear, crisp images within a user interface web view

I currently have a webview that is set up to show an image, which can be seen in the code snippet provided below. Along with this image, there is also a [email protected] available in the bundle, sized at 128x128 for use specifically on the iPhone4 ...

Tips for extracting information from a SharePoint list using JavaScript and jQuery

As a beginner in SharePoint, I am looking to use JavaScript and jQuery to retrieve data from a SharePoint list and display it on a webpage. ...

Leveraging sessions within the CSS Declaration

Struggling to pass the css file name to my razor page through session. Here's what I've got: Current line of code: <link href="@Url.Content("~/Content/epp.css")" rel="stylesheet" type="text/css" /> Trying to pass 'epp' as a Ses ...

displaying dropdown menu from bootstrap 4 on top of a div located below

Struggling to make the bootstrap 4 responsive top nav appear over my container div, but can't find a solution. This is how the Top nav should function: W3Schools editor Here is my code on jsfiddle: jsfiddle function myFunction() { var x = ...

Ways to animate elements while scrolling in React.js?

I am new to using React.JS and currently working on setting up an E-commerce Store. My goal is to have 5 images stack on top of each other and move together as the user scrolls. I used to achieve this effect in Vanilla JavaScript by adding a window.addEven ...

Text area featuring unique border design, with border color change upon focus?

Currently, I have a text area with borders that are designed in a unique way. However, I am looking to change the border color when the user focuses on the text area. Do you have any suggestions on how I can achieve this effect without affecting the curre ...

Using CSS to place my logo within the navigation bar

Currently, I am struggling to find tutorials that can assist me in aligning the responsive navigation bar with the logo. As a newcomer to HTML & CSS and website creation, I would greatly appreciate any guidance on positioning it correctly. Additionally, co ...

A guide to integrating the YouTube player and Facebook API with Bootstrap 3

Hello everyone! Hey there, I'm Cody, a student and amateur web designer. I recently got the opportunity to work on a website for a family friend. I've been using bootstrap3 to ensure the site is responsive, but I've run into an issue while ...

Complete picture in a circular div with aspect ratio

I'm currently working on creating a profile page and I'd like to have an image inside a circular div. The challenge is that I want the image to maintain its aspect ratio, even though the dimensions are unknown and users can upload images of any s ...

accessing PHP array elements within JSON

How can I access an array of arrays returned from PHP in JSON format? This is the PHP array: $cities = array(); while($row = mysql_fetch_array($result)){ $cityRow= array('cityNo'=>$row['city_no'], 'cityName'=>$row[ ...

Revolutionary AJAX technology seamlessly updates and refreshes elements within every row or form on a webpage

<script type="text/javascript"> $(document).ready(function() { $("#submit<?php echo $resultshome['hskid']; ?>").click(function() { $.ajax({ type : "POST", url : "/scores/printPOST.php", data : { "subro ...

Running JavaScript code for the iframe

Question about Manipulating Content in an iFrame: Invoking javascript in iframe from parent page I am attempting to load a HTML page with an iFramed website and then manipulate the content by removing an element, referred to as '#test'. < ...

Retrieving HTML table data using PHP

In the scenario where I have an HTML form with a table like the one below: <form method="POST" action="a.php"> <table name="dataTable"> <tr> <td>row one col one</td> <td>row one col two</td> <td>row o ...