Scrolling with JQuery between a webpage's header and footer

I'm having trouble keeping a div at the top of my page, but I want it to stop scrolling before reaching another div.

<div class="my-top"><p>This is the top</p></div>
    <div class="big-one">
        <div class="mini1">
            <p>TEST 1</p>
        </div>
        <div class="mini2">
            <div id="mini-mini2">
                <p>Need to scroll</p>
            </div>
        </div>
    </div>
    <div class="my-footer">
        <p>This is the footer</p>
    </div>

Check out this fiddle for reference: https://jsfiddle.net/2q773opz/3/

Despite my efforts, when I scroll, the div moves down and then returns to the top instead of stopping at "mini2". Any advice would be greatly appreciated. Thank you!

Answer №1

By setting the parent of #mini-mini2 to have position:relative, you can position #mini-mini2 absolutely within it. Then, your JavaScript can set the element's position top to be the current scrollTop minus the header height, ensuring that #mini-mini2 does not get pushed too far.

To see this concept in action, check out the example below:

$(document).ready(function() {
    var breaking = $('.big-one').offset().top;
    var limit = $('.my-footer').offset().top - $('#mini-mini2').height();
    $(window).scroll(function() {
        var scrolltop = $(window).scrollTop();
        var top = scrolltop - breaking;
        if (scrolltop > breaking && scrolltop < limit) {
            $('#mini-mini2').css("top", top);
        }
    });
});
.my-top,
.my-footer {
    width: 100%;
    height: 50px;
    border: 1px solid;
}

.my-top {
    height: 250px;
}

.my-footer {
    height: 450px;
}

/* Additional CSS styles */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-top">
    <p>
        This is my top
    </p>
</div>
<div class="big-one">
    <div class="mini1">
        <p>
            TEST 1
        </p>
    </div>
    <div class="mini2">
        <div id="mini-mini2">
            <p>
                Need to scroll
            </p>
        </div>
    </div>
</div>
<div class="my-footer">
    <p>
        This is my footer
    </p>
</div>

View the updated jsFiddle for further reference: Updated jsFiddle


UPDATE

A more precise approach involves toggling the elements between position:fixed and adjusting top vs bottom positions in order to prevent misalignment of #mini-mini2 when scrolling too quickly. Check out the updated code snippet below:

$(document).ready(function() {
    var breaking = $('.big-one').offset().top;
    var limit = $('.my-footer').offset().top - $('#mini-mini2').height();

    $('#mini-mini2').css("width",$('.mini2').width());
    $(window).resize(function() {
    $('#mini-mini2').css("width",$('.mini2').width());
    });
    $(window).scroll(function() {
        var scrolltop = $(window).scrollTop();
        var top = scrolltop - breaking;
        if (scrolltop > breaking && scrolltop < limit) {
            $('#mini-mini2').addClass("fixed");
        $('#mini-mini2').css("bottom", "auto");
            $('#mini-mini2').css("top", 0);
        } else if(scrolltop > breaking) {
        $('#mini-mini2').removeClass("fixed");
        $('#mini-mini2').css("bottom", 0);
            $('#mini-mini2').css("top", "auto");
        } else {
        $('#mini-mini2').removeClass("fixed");
        $('#mini-mini2').css("bottom", "auto");
            $('#mini-mini2').css("top", 0);
        }
    });
});
.my-top,
.my-footer {
    /* Styles for .my-top and .my-footer */
}

/* Additional CSS styles */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-top">
    <p>
        This is my top
    </p>
</div>
<div class="big-one">
    <div class="mini1">
        <p>
            TEST 1
        </p>
    </div>
    <div class="mini2">
        <div id="mini-mini2">
            <p>
                Need to scroll
            </p>
        </div>
    </div>
</div>
<div class="my-footer">
    <p>
        This is my footer
    </p>
</div>

For the latest version, visit: Updated jsFiddle

Answer №2

If you want to restrict the downward scroll behavior, you can remove a class when the scrollTop() value of the window exceeds the top position of the .my-footer element by the height of the #mini-mini2 element. You can achieve this by implementing the following solution:

$(window).scroll(function() {
    var $mini = $('#mini-mini2');
    var toggle = $(window).scrollTop() >= breaking && $(window).scrollTop() <= (limit - $mini.height());
    $mini.toggleClass("floatable", toggle);
});

Check out the updated code snippet here!

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

Ways to extract information from a dynamically loaded webpage

Is there a way to extract data from a news website that automatically reloads at set time intervals? I want to use this data on my own website as information, whether it's in the form of images or text. Can anyone guide me on how to retrieve data from ...

Challenges encountered while attempting to animate the CSS clip feature in WebKit

I've been searching everywhere for a solution to my issue, but none of them seem to work. As someone new to CSS3 Animations, I appreciate your patience. I created a simple animation using CSS3 that functions perfectly in IE and Firefox, however, it ...

When using `$(".sth").attr("id")`, the function may return various values, with undefined being the first

When running the code below, it triggers two alert boxes. The first one displays undefined, while the second one shows the id attribute. However, when adding return false at the end of the script, it only presents undefined and does not return the id value ...

Having trouble getting the form input max-width to work properly within a flex-box

My webpage features a header containing various icons, a title, and a search box that triggers an animation when the search button is clicked. While this setup works seamlessly on larger screens, I encounter issues on smaller screens. My goal is for the se ...

Managing two variables in C# Controller and View

I am facing an issue with the two variables in my controller class. The first variable, currentUserId, is supposed to store the user currently logged into the website. The second variable, currentRoomId, should track the chat room the user is in. The probl ...

Ways to resolve the issue of data-bs-target not functioning properly in Bootstrap version 5

While viewing the Job screen in the following image, I attempted to click on "Personal," but it remained stuck on the Job screen. ...

My JSON file is being populated with duplicate data when making an AJAX post call

I encountered an issue while working on my project. I am trying to create a news article archive using node.js. I capture all the necessary data from a form and store it in a JSON file. Here is a simplified version of my form: <form id="json-form&q ...

Difficulty with Vue.js updating chart JS label names

I have been working with Vue JS and implementing a chart in my single page application. However, I am encountering difficulties updating the Legend and despite numerous attempts and searches, I am unable to get it to update. Any assistance in correcting my ...

How to retrieve a value from ng-options using AngularJS?

I want to display a dropdown in which users can select a specific month. Currently, the dropdown is populated with all 12 months in an array. How can I make sure that only the selected month is fetched from the dropdown? Code Snippet: $scope.Month = [&ap ...

Set values for scope variables that are created dynamically

I am currently working on a solution to toggle dynamically generated rows of data. I have attempted using ng-init and passing it to a function, but I seem to be making a mistake somewhere and struggling to understand if this is even feasible. The issue see ...

Extract JSON from the response data in the success callback of a JQuery.ajax

I've encountered an issue with retrieving the contents of a JSON object from a JQuery.ajax call. Here is my code: $('#Search').click(function () { var query = $('#query').valueOf(); $.ajax({ url: '/Products/Se ...

Enhance your webpage with a stunning background video

I'm trying to add a background video that covers the entire screen but maintains a height of 400px, similar to the one shown here. Is there a way to achieve this without using JavaScript? Below is the HTML code I currently have: <div class="pr ...

Position the div beneath another div using the display:grid property

I can't seem to figure out how to position a div below another div using display:grid. The div is appearing on top instead of below. The "app-bm-payment-card-item" is actually a custom Angular component. Here's the HTML file: //div wrapper < ...

Exploring the process of dynamically updating a form based on user-selected options

I need assistance with loading an array of saved templates to be used as options in an ion-select. When an option is chosen, the form should automatically update based on the selected template. Below is the structure of my templates: export interface ...

Issue with Displaying Background Image

When trying to set my background image on CDM using document.body.style={mainBg}, I am not getting the expected result. Additionally, the console statement below it is printing out an empty string. Can anyone assist me in identifying what mistake I might b ...

I must align a bootstrap modal(dialog) based on the opener's position

Using a bootstrap modal for the settings dialog in an angularJS app, but facing an issue where it opens in the center of the page by default instead of relative to the opener. Looking for a solution to keep it positioned correctly when scrolling. Code: M ...

Vue3: Pinia store data not being received

Having trouble retrieving Pinia data using the Composition API after a page reload? I'm utilizing Vue to parse fetched JSON data. Despite being new to the Composition API, I can't pinpoint what's causing the issue even after going through th ...

Activate Bootstrap tab form with the ability to include sub tabs for added functionality

I have been working on a method to open Bootstrap 3 tabs on my pages based on the URL. For example, if the URL is myurl.com#tab1 (it will open the tab with id #tab1). Here's the code I am using: $(function () { var hash = window.location.hash; ...

When attempting to call an API using the Angular HttpClient, an issue is encountered

I am having trouble displaying my JSON data in my application. I have imported the HttpClientModule in app.module.ts, but I keep getting an error that says: "" ERROR Error: Cannot find a differ supporting object '[object Object]' of ty ...

What methods can be employed to ensure that the DRF (Django-REST-Framework) Token remains intact and does not disappear with each page refresh?

IMPORTANT: I am utilizing Pure HTML+jQuery+AJAX without Python, Django, or Templates for the front-end development. I have successfully managed to retrieve a User-Based Token from the API Backend, inserted it into the Header File for subsequent requests, ...