Repairing div after upward scrolling and maintaining its fixation after refreshing the page

I have encountered two issues with this particular example:

  1. One problem is that the fixed_header_bottom should stay fixed beneath the fixed_header_top when scrolling up, causing the fixed_header_middle to gradually disappear as you scroll up, or vice versa. Interestingly, this function works on my computer but not on JSFIDDLE for some unknown reason! Hence, I had to adjust it accordingly.

  2. The second issue arises when refreshing the page while the cursor is positioned at the bottom; the fixed_header_bottom should still remain fixed below the fixed_header_top. Strangely, this only fails in the Opera browser (version 12.16), whereas other browsers handle it fine.

You can view the JSFIDDLE here

To address these problems, how can I solve them?

Javascript:

$(window).load(function ()
{
    $(document).ready(function ()
    {
        $(window).bind("scroll", function (e)
        {
            if (! $('#fixed_header_bottom').hasClass('fixed'))
            {
                if ($(document).scrollTop() >= 300)
                {
                    $('#fixed_placeholder').show();
                    $('#fixed_header_bottom').addClass('fixed');
                }
            }
            else
            {
                if ($(document).scrollTop() < 300)
                {
                    $('#fixed_placeholder').hide();
                    $('#fixed_header_bottom').removeClass('fixed');
                }
            }
        });
    });
});

CSS:

*
{
    margin: 0;
    padding: 0;
}
#fixed_header_top
{
    display: block;
    position: fixed;
    width: 100%;
    height: 50px;
    background-color: #DD33DD;
    top: 0px;
}
#fixed_header_middle
{
    display: block;
    width: 100%;
    height: 300px;
    background-color: #DDDD00;
    margin-top: 50px;
}
#fixed_header_bottom, #fixed_placeholder
{
    display: block;
    width: 100%;
    height: 50px;
    background-color: #11DD55;
}
#fixed_placeholder
{
    display: none;
}
.fixed
{
    position: fixed;
    top: 50px;
}
#body_block
{
    display: block;
    width: 100%;
    background-color: #FFFFFF;
}

HTML:

<div id="fixed_header_top">fixed_header_top</div>
<div id="fixed_header_middle">fixed_header_middle</div>
<div id="fixed_header_bottom">fixed_header_bottom</div>
<div id="fixed_placeholder">Shouldn't see me</div>
<div id="body_block">BEGIN
    <br />
    <br />Bottom
    <br />Bottom
    <br />Bottom
    <br />Bottom
    <br />Bottom   [truncated for brevity]   END
</div>

Answer №1

Include the following jQuery snippet in your code:

if($('#fixed_header_bottom').offset().top<=50) {
      $('#fixed_header_bottom').addClass('fixed');
} else {
      $('#fixed_header_bottom').removeClass('fixed');
}

You can view the example in action on this fiddle: http://jsfiddle.net/6KAdU/5/

Remember: Placing $(document).ready() within $(window).load() is unnecessary.

Answer №2

One clever trick is to store the last window scroll position in a cookie so that you can easily retrieve and set it when needed.
This method has proven to be quite effective.
Another option is to use an HTML anchor link like this:

<div id="mysection" ></div>

<a href="#mysection" >Link to Section with 'mysection' id </a>

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

Exploring the limitations of middlewares in supporting independent routers

When I examine the code provided, it consists of three distinct routers: const Express = require("express") const app = Express() // Three independent routers defined below const usersRouter = Express.Router() const productsRouter = Express.Router() cons ...

Implementing a peculiar timing mechanism with the integration of socket.io, jQuery Mobile, and the socket.emit() function

Currently in the process of working with cordova and node.js socket.io, I encountered a peculiar issue with socket.emit(); The following code fails to enter 'room', despite having correct coding: client-side jsfile.js //Two global variables fo ...

getting v-model value updated when clicking button

How can I update the value of v-model DataJournals.Description in a looping data when a button is clicked? This is what I have attempted: template <tr v-for="(DataJournals, index) in DataJournal" :key="DataJournals.value"> <td> & ...

Error in Wordpress Frontend Ajax: The variable ajaxurl is not defined in wp_localize_script

My current challenge involves creating markers on a map using ajax within a Wordpress theme. Despite several attempts, I discovered that I cannot utilize a PHP file to retrieve data via ajax; instead, I must use the admin-ajax.php file. Following numerous ...

Implementing JavaScript functionality based on a specific body class

Is there a way to execute this script only on a specific page with a particular body class? For example, if the page has <body class="category-type-plp"> How can I target my script to work specifically for "category-type-plp"? plpSpaceRemove: fun ...

Change the WordPress Divi Builder nav bar to switch from transparent to white when scrolling or upon reaching a specific point on the page

Currently, I am in the process of revamping our company's WordPress website using the Divi Builder. For the past couple of days, I have been scouring the internet trying to find a solution that would allow the navigation bar to change CSS classes as t ...

Switching the position of a Button in Semantic UI React: Moving it from the Left to the

I need assistance with adjusting the position of a Semantic UI React Button. By default, the button is displayed on the left side, but I would like it to be on the right side instead. Can someone please provide guidance on how I can move the Semantic butto ...

A particular character is displayed exclusively in a text box using either jQuery or JavaScript

Text Box <input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" /> Solution Using jQuery or Javascript: var readOnlyLength = $('#txtbo').val().length; $('#txtbo').on('keypress, keydown', function(even ...

Utilizing a foreach loop to control the behavior of two distinct radio buttons as a unified

Can someone help me with a code containing a 5 star rating system (radio button) for two different questions? The issue is that the ratings for each question are linked, so when I make a selection in one question, it clears the selection in the other. It& ...

Sorting through an array of JavaScript objects and aggregating the step values for matching user names

Currently, I am delving into JavaScript and facing a certain challenge that may be considered easier for seasoned developers. My goal is to iterate through an array of objects, filter out objects with the same userName, and then aggregate their steps. The ...

Unable to download the jQuery Plugin

I am looking to install a gallery without using flash, and I came across this jQuery plugin called Grid-A-Licious. However, I am having trouble figuring out how to install and use it since it is distributed as a .zip archive with two .js files but no index ...

Having trouble with AngularJS $location.path() not redirecting properly?

Why am I unable to redirect to a different URL using $location.path in angular.js? .controller('CheckCtrl', function($scope, $localStorage, $location) { $scope.check = function(){ if($localStorage.hasOwnProperty("accessToken") === t ...

Node.js - Headers cannot be sent again once they have been sent

I came across a similar issue to mine at this link. I suspect that the error is occurring due to how my .end() calls are configured. Let's take a look at the code in question: app.get('/anihome',function(req,res){ var context = {}; functi ...

Transfer the information on the onClick event to the loop's function

When creating my component within the parent component, I follow this approach: renderRow(row){ var Buttons = new Array(this.props.w) for (var i = 0; i < this.props.w; i++) { var thisButton=<FieldButton handler={this.actionFunction} key={&ap ...

The selection in one dropdown menu influences the options in another dropdown menu

My partner and I have teamed up to develop a React translation application that utilizes the Lexicala API. Our project includes two selector components: one for choosing the source language and another for selecting the target language. Users will first pi ...

Protractor's modal dialogue displays numerous outcomes when accessing ng-repeater elements

Trying to click on an element located within a repeater has presented some challenges. The issue arises from the fact that it is a modal dialog and returns multiple elements for the repeater. Each page in our application functions as a modal dialog, leadin ...

The scroll function malfunctions when attempting to center-align content on the screen with the use of transform

Is there a way to center a div on the screen without encountering scrolling issues when the screen size is reduced? If you have any alternative solutions (excluding the use of transform), please share, as I've tried various approaches but have not be ...

What is the best method for retrieving data from a specific collection in MongoDB?

Within the code snippet below, on the 4th line, 'Messages' is the name of my MongoDB collection that I created in another file. When I attempt to retrieve data from this collection, no errors occur. However, when I specify the name of a differen ...

Store the order of sortable items in a MySql database using Jquery UI

I am currently utilizing JQuery UI Dragabble, Droppable, and Sortable for my project. There are two distinct sections on my PHP file where I drag and drop content from the bottom to the top div section. Within the top div section, I am conducting Sortable ...

The structure of NodeJS Express API calls revolves around handling asynchronous events

Currently, I am working on a hobby project using NodeJS and Express, but I am finding it challenging to manage asynchronous calls. There is a bug that I would like the community's help in resolving. I have set up an Express layout where I send post r ...