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

Navigating through images within my application

When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...

Navigating between two table components in React JS

I am a beginner in the world of React and I am struggling with switching between these two tables. Despite consulting the documentation for inline conditional statements, I still couldn't figure it out. My goal is to have the tables switch after click ...

Click on the logo to return to the home page

Logo Link Causing Menu Alignment Issue After setting the logo as a link, the menu unexpectedly shifts to the right. Upon inspecting the menu element, it appears that there is an additional hidden menu link on the left side leading to index.html. Can anyon ...

I am looking to update the appearance of a button dynamically in Vue.js based on changes to an

Is there a way to toggle a visible button when the array changes? I'm having trouble implementing this. What is the most effective method? Check out my example below: https://codesandbox.io/s/relaxed-poincare-vv6xh?file=/src/components/HelloWorld.vu ...

Is there a way to extract just the first line or n characters from a JSON file without having to download the entire dataset?

I am looking to extract specific information from a large JSON file that is 450 KB in size. However, I do not need to download the entire JSON file as I only require certain characters or lines from it. Is there a way to read n characters or line by line ...

What is preventing me from navigating to other pages in my React application?

Recently, I have been experimenting with ReactJS and encountered an issue where I couldn't access my other pages. The code snippet provided below seems to be the root of the problem. I am in the process of developing a multi-page application using Re ...

The Zustand store does not reflect changes when the URL is updated

I have a Zustand store connected to the URL. See the code snippet provided below. import { create } from "zustand"; import { persist, StateStorage, createJSONStorage } from "zustand/middleware"; const pathStorage: StateStorage = { ge ...

Minor Chrome compatibility problems with CSS alignment

As someone who is new to stackoverflow, I've always found it to be a valuable resource for answers. I've had success building HTML 5 banner ads using GSAP (Greensock Animation Platform) in the past, but now I'm facing a CSS alignment issue t ...

Unraveling the mysteries of deciphering extended JSON information

Issue with Data Interpretation I am facing a challenge in my project that is more related to understanding and interpreting data rather than writing code. The project involves using a NoSQL database, specifically MongoDB, to store information sampled from ...

Creating or updating JSON files using Node.js

I am currently working with JSON files that contain an array of objects. I am looking to update one of these objects and subsequently update the JSON file by overwriting the old file. I understand that this cannot be achieved using AngularJS, but rather wi ...

Utilize React without integrating a router component

For my web application built with reactjs, I am considering creating a multi-page site rather than a single page. Should I bundle all the react code into one file and include it on every page of the application, then utilize the exposed function to render ...

Restrict the number of dynamic form elements to a maximum of 10 entries

I am working on a feature where users can refer their friends and the data will be saved in a database. <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type='text/javascript' sr ...

li tag style

I need to insert a check mark inside the <li> tag on the right side. How can I do this? The check mark looks like this: For example: http://jsfiddle.net/HpVcy/ ul li{ padding: 3px 10px 3px 10px; background:url(http://img4up.com/up2/730897458613759 ...

Choosing a lone column in amcharts 4

Is there a way to highlight just one column and unhighlight any previously highlighted columns in an amCharts 4 Column chart? I've been attempting to adjust the colors of all the columns before highlighting the target column, but it doesn't seem ...

Utilizing JSON and Javascript to dynamically generate and populate interactive tables

Here's how I've structured my JSON data to define a table: var arrTable = [{"table": "tblConfig", "def": [{"column": "Property", "type": "TEXT NOT NULL"}, {"column": "Value", "type": "TEXT NOT NULL"}], "data": [{"Property ...

Having trouble accessing properties of an undefined object when trying to read 'credentials' in Firebase Auth within ReactJS

I need to verify the user's password again before allowing them to change it. Currently, my Firebase Auth setup is defined in Firebase.js and exported correctly //appConfig = ...(all the configurations here) const app = firebase.initializeApp(appConf ...

Elements featured in the header: logo, tagline, graphics, and more

I'm interested in designing a schema with the following elements: I'm contemplating whether it would be beneficial to have a separate container for the logo and slogan. Additionally, I am considering if it is advantageous to create a container f ...

Determine the file format using fs module in Node.js

I have a question about extracting file types or extensions from a folder. I have multiple files in a folder, and I want to retrieve the type/extension of the file that matches a randomly generated number stored in my num variable. Is there a way to achiev ...

Outlook for Windows automatically sets the default font for HTML emails to Times New Roman

My email design looks great in Mac Outlook, but Windows Outlook is changing the font to Times New Roman. Below is the code for the email template. Can someone help me figure out what I'm missing? <style style="-ms-text-size-adjust: 100%;&q ...

Using query parameters in Angular to interact with APIs

One scenario involves a child component passing form field data to a parent component after a button press. The challenge arises when needing to pass these fields as query parameters to an API endpoint API GET /valuation/, where approximately 20 optional p ...