Scroll the div until it reaches the top of the page, then make it fixed in place

Let's dive right in:

The code I am working with is as follows:

<div id="keep_up">
    <div id="thread_menu">
        <div id="new_thread">

        </div>
    </div>
</div>

And here is my CSS:

#keep_up {
    position: fixed;
    width: 13%;
}

 #thread_menu{
     height: 80vh;
     width: 100%;
     float: left;
     position: relative;
}

I am using this for a forum to display active and new threads on the screen. The issue arises when viewing a thread, causing the header to disappear (expected behavior due to scrolling).

However, I want the thread menu to remain visible at all times by sticking to the side of the screen. This is achieved by setting my keep_up div to position: fixed. But because the menu is too long, it does not scroll up entirely.

My inquiry:

I aim to have the thread menu scroll up until it reaches the top of the window, after which it should stay there. How can I achieve this?

I have attempted various methods but none seem to work for me. Here is the code I tried:

<script src="jquery.min.js">
    $(window).scroll(function () {
        var margin = null;
        $(window).on("scroll", function () {

            var scrollHeight = $(document).height(),
                scrollTop = $(window).scrollTop(),
                offsetBottom = 110,
                offsetTop = 100,
                positionTop = $(".keep_up").offset().top,
                affix;


            if (margin != null && (scrollTop + margin <= positionTop)) {
                affix = false;
            } else if (positionTop + $(".keep_up").height() >= scrollHeight - offsetBottom) {
                affix = 'bottom';
            } else if (scrollTop <= offsetTop) {
                affix = 'top';
            } else {
                affix = false;
            }
            
            if ($(".keep_up").hasClass('at' + (affix ? '-' + affix : ''))) return;

            if (affix == 'bottom') {
                margin = positionTop - scrollTop;
            } else {
                margin = null;
            }
            
            $(".keep_up").removeClass('at at-top at-bottom').addClass('at' + (affix ? '-' + affix : ''))

        });
    });
</script>

And the corresponding CSS:

.keep_up{
    /*position: fixed;*/
    width: 13%;
}

.keep_up.at {
    top: 1px;
    position: fixed;
}

.keep_up.at-top{
}

.keep_up.at-bottom {
    top: 438px;
    position: absolute;
}

Answer №1

Update this in HTML:

<div id="prevent"></div>
<div id="keep_up" data-spy="affix" data-offset-top="200">

Include this CSS:

.affix{position: fixed !important; top:0px; z-index:999;}
.affixpatch{margin-top:100px !important;}

This code will make the div fixed when scrolling down 200px. Adjust the data-offset-top value for different breakpoints. .affixpatch is a supplementary class to ensure content doesn't hide behind the fixed div. Modify margin-top if needed to prevent any "hide content" issues that commonly occur with affixed elements.

<script>
$(function() {
    var header = $(".affix");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();
        if (scroll >= 200) {
            $('#prevent').addClass("affixpatch");
        } else {
            $('#prevent').removeClass("affixpatch");
        }
    });
});
</script>

Hope this explanation proves helpful. If not, there might be conflicts with other classes affecting the functionality of this affix feature.

I've extensively tested this solution, particularly for fixing navbars.

SCROLL: Implementing overflow for scrolling content:

#keep_up{
   max-height:400px;
   width: auto;
   overflow:auto;}

This setup enables scrolling within the #keep_up div (or a similar one). NOTE: A specific maximum height must be defined for this div. Specify a maximum width as necessary. Use various units like %, em, rem for responsive design - not limited to pixels.

Answer №2

Based on my understanding of your situation, you can achieve this by utilizing jQuery (or native JS, but since you have tagged jQuery I will assume you prefer that).

There is a useful plugin designed for handling such tasks:

I recommend examining the source code of the plugin to grasp its functionality - it involves an event handler function on $(window).scroll() that manipulates classes on your #thread_menu element to make it sticky in position. To keep your code efficient, you may not require all features offered by the plugin.

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

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

Avoiding the <br> tag in list items with TinyMCE

I am currently using tinyMCE and I needed to enable the "force_br_newlines: true" option. Without this setting, if I press the "Enter" key twice and check the source code, I only see one <br> tag. However, when I set the option to TRUE, it creates a ...

Run a jQuery script that is inserted dynamically after the page has finished loading

I am currently working on a website that is utilizing ajax requests to dynamically update specific sections of the page. One particular request involves generating an extra jQuery script and injecting it into the document. I am struggling to find a soluti ...

What is the best way to integrate JavaScript and Python for seamless collaboration?

I'm looking to create a bidirectional communication model between JavaScript and Python. The idea is for JavaScript to handle data processing, send it to Python for further processing, and then receive the results back from Python. However, I'm u ...

What factors cause variations in script behavior related to the DOM across different browsers?

When looking at the code below, it's evident that its behavior can vary depending on the browser being used. It appears that there are instances where the DOM is not fully loaded despite using $(document).ready or similar checks. In Firefox, the "els ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

What causes the alignment of text to be overridden by the presence of a floating element?

https://jsfiddle.net/u0Ltgh3e/68/ .text { width: 50%; text-align: justify; } I am currently developing a custom formatting tool for a specific purpose and I am attempting to create a two-column layout similar to the one demonstrated in this Jsfiddle l ...

I must remove the thumb from the input range control

I am looking for a way to remove the thumb from the progress bar in my music player. I have tried various methods without success, and I simply want the progress bar to move forward with color change as it advances based on the Progress variable. For refe ...

Encountering an issue in XtermJS where it is unable to read properties of undefined, specifically 'dimensions', while being used with NextJs version 14

UPDATE: Additional Details useEffect(() => { // let terminal; if (terminalRef.current) { const terminal = new Terminal({ fontFamily: "Menlo, Monaco, monospace", // fontSize: 12, // cursorBlink: true, ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...

The dictionary of parameters includes an empty value for the parameter 'imageWidth', which is of a non-nullable type 'System.Int32'

I am facing an issue with a function that executes an ajax call to an ActionResult. It sends a base64 string of an uploaded image along with some additional parameters containing information about the dimensions of the image. The data is sent to the server ...

Guide on extracting unique key values from an array by utilizing a different key

I have an array containing the names of products along with their storage capacities. let products = [{name: "samsung A", storage: "128GB"}, {name: "samsung B", storage: "128GB"}, {name: "samsung C", storag ...

Trigger Chrome Extension Background Page Using a Message

Currently, I am in the process of developing my initial chrome extension and focusing on establishing message passing and background.js functionality. However, it seems like my background.js file is not being triggered or receiving any messages. I am seeki ...

Tips for utilizing fontawesome effectively in a select menu

I'm having trouble displaying fontawesome icons in a select element, as they do not appear correctly in the drop-down list. .FontAwesomeSelect { font-family: Font Awesome\ 5 Free; font-size: 18px; } <link href="https://use.fontaw ...

Update issue detected with radio buttons in jQuery

Trying to get radio buttons in my code to update like other variables on the web page when their state changes. HTML <TD><Input id="radOn2" name="Nb_var86" type= "radio" Value=1 onClick="this.form.submit();">ON</TD> <TD><Input ...

Updating the Document Object Model

React re-renders only when there is a change in state. However, it may seem like the changes made directly to the real DOM reflect instantly. This might raise questions as to what triggers the re-render when the state remains unchanged. import React from ...

Managing a variable amount of form input values

One of the challenges I'm facing is handling a form that includes a link to open a modal window for entering additional information. Since this additional information is generated dynamically, I need to find a way to create these items as they are add ...

The Nextjs Image was preloaded using link preload, but it remained unused after a short period following the window's load event

I've encountered an issue while working with Next.js, a React-based framework. I am attempting to display the logo.png image using the Image component provided by Next.js. My image is stored in this folder: public/img Here is the code I'm using ...

What is the best way to add a new project and make updates to an existing project within an array?

Looking to add a new project and update existing projects within an array. Here's my plan in pseudo-JSON format. How can I update Project A in MongoDB? { _id : ..., userName: milad , projets : [ { .. projectId, pName, location .... A }, ...

The suggestions are not being displayed by jquery-typeahead

I have integrated jquery-typeahead into my Angular application. Here is the HTML: <input class="js-typeahead-locations_v1" name="locations_v1[query]" type="search" placeholder="Search here" autocomplete="off"> The controller code snippet is as fol ...