Ensure the top element remains fixed until the page scrolls (once the content surpasses it)

To ensure that all page content (highlighted in red as "Test" in the image) is placed at the top 100% and requires scrolling to view.

The top header (identified in black in the image) should be fixed at the top of the page.
When the content reaches the header, it should start scrolling along with the rest of the content.

(I am unsure where to begin in solving this issue... Is there a way to achieve this without JavaScript?)
Thank you in advance for any assistance provided.

Answer №1

I've discovered a clever technique using a few lines of JavaScript:

Live demo on jsBin

var headerFixed = document.getElementById("headerFixed");
var headerClone = document.getElementById("headerClone");

headerClone.innerHTML = headerFixed.innerHTML;            // Clone the header content (good for SEO)

function adjustHeaderOpacity(){
  var topPos = headerClone.getBoundingClientRect().top; // Keep track of the clone's top position
  headerFixed.style.opacity = topPos<0 ? 0 : 1;         // Toggle original header opacity
  headerClone.style.opacity = topPos<0 ? 1 : 0;         // Toggle cloned header opacity
}

adjustHeaderOpacity();                 // Execute when DOM is loaded
window.onscroll = adjustHeaderOpacity; // Execute on scroll
window.onresize = adjustHeaderOpacity; // Also execute on resize

The idea behind it:

      +--  +----------------+-- (Viewport Top)
      |    |   headerFixed  |   opacity:1; goes to 0 when the Clone reaches Viewport Top
      h    +----------------+
      e    |                |
      r    |                |
      o    +----------------+
      |    #   headerClone  |   opacity:0; goes to 1 when it reaches Viewport Top
      +--  +----------------+-- (Viewport Bottom)
           |   Content...   |   
           ⋮                 ⋮         

HTML structure:

<div id="hero">
    <div id="headerFixed"><h1>Header</h1></div>
    <div id="headerClone"></div>
</div>
<div id="content">Website template and content go here</div>

CSS styling:

html, body { height:100%; }
#hero{              
    height:100%;       
}
#headerFixed {
    position: fixed;   
    width: 100%;
}
#headerClone{         
    position:absolute; 
    bottom:0;          
    opacity:0;         
    width:100%;
}

Hint: if the explanation above is unclear, try adding different background-colors to all elements. It will help visualize what's happening.

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

Using the detach() function followed by append() with the <picture> tag in Safari leads to the unnecessary downloading of a JPG file twice

Max OS version: 10.14.3 Safari version: Version 12.0.3 (14606.4.5) I'm encountering a unique issue specific to Safari. My use of jQuery's detach() and append() on a picture tag is causing Safari to make duplicate image requests, which is unexp ...

Issue with event.preventDefault() in Jquery not functioning as expected

My goal is to have the menu display and hide list items on click, with them being hidden by default. However, the issue I am facing is that the menu is generated in the admin section, so it automatically assigns a URL to each item. If I set the URL field o ...

What is it about the appearance of buttons in Chrome that doesn't quite match up to how they look in

I am struggling to make my button display the same in Chrome as it does in Mozilla Firefox. Here is the CSS code I am using: .myButton { font-size: 14px; background:#e3e3e3; color:gray; padding:11px; margin-right: 0; width: 1 ...

What is the best way to make an element disappear 5 seconds after the mouse has stopped hovering

#section1 { display: block; } #section2 { display: none; } #container:hover > #section2 { display: block; } <div id="container"> <div id="section1">Section1</div> <div id="section2">Section2</div> </div> ...

Increase the size of the image when scrolling

My application features a collection of 10 images, all sized at 200px x 200px. One functionality I am trying to implement is increasing the size of the top image to 400px x 400px when scrolling. Currently, I have code in place to detect if a div is visibl ...

Troubleshooting problem with Snapjs Drawer and navigating through scrolling content

Currently, I am utilizing Snap JS to implement a drawer on the left with content displayed on the right. Despite this setup, I am encountering an issue where scrolling is still enabled for the content on the left when the drawer is open. I am seeking guid ...

Height Mismatch in Nested Div Elements

How can I make the container div resize to fit its contents (content div)? I've tried but it doesn't seem to work. Here's an example in example.html: <html> <head> <link href="example.css" rel="stylesheet" type=" ...

Navigate to the following div elements using the mousewheel in jQuery

Looking to implement a parallax effect where the page scrolls to the next block on each mousewheel rotation. I attempted to achieve this using the code below but it didn't work as expected. Can someone offer any suggestions? Check out the live JSFid ...

What is the best way to retrieve past data using RTK Query?

When working with data retrieval using a hook, my approach is as follows: const { data, isLoading } = useGetSomeDataQuery() The retrieved data is an array of items that each have their own unique id. To ensure the most up-to-date information, I implement ...

The issue arises when the Javascript function is triggered twice, resulting in only 3 out of 4

I'm currently working on a JavaScript calculator project. Everything is running smoothly except for the add() function (subtraction, multiplication, and division are all functioning properly). Additionally, when I hit "=" it displays the answer twice ...

Finding the most recent instance of a deeply buried value based on a specific property

I have an example object: const obj = { group: { data: { data: [ { id: null, value: 'someValue', data: 'someData' } ...

Best practice for showcasing the output of an array in Javascript

My variables are defined in an array like this: const nbActions = 13; const sdgValues = ['1', '2', '5', '6', '3', '0', '2', '0', '0', '6', '0', & ...

Is there a way to inject C++ text into an input field on a webpage using QWebEngine?

I want to integrate a website with QWebEngine to manipulate input commands using Qt's event filters and more. The specific website I am working with requires a username/email and password, and I aim to manage the input of this text on my end. This inv ...

The dimensions of the image are determined by its orientation

I am working with two different types of images on my website: vertical and horizontal. Currently, I have a JavaScript function that adjusts the height of all images to fit the screen size. However, I would like to modify this function so that it also adap ...

Sophisticated method in JavaScript to conceal and reveal div elements

My knowledge of front-end web development is strongest in HTML and CSS, but when it comes to JavaScript, I feel like there must be a more efficient way to achieve the functionality I want. On my website, I have a set of <li> items that, when clicked ...

Using a 100% width setting will only occupy half of the screen on mobile devices or laptops

It should actually be slightly less than 100% because setting it at 100% causes the content to be off screen to the right. When I view my page on a tablet or laptop, it zooms into the top left corner of the screen. If I zoom out, I notice that the divs o ...

What steps can I take to stop text from disappearing when the screen size decreases and the span is used?

I'm currently using Bootstrap 5 to create a form. On a computer screen, my file input element looks like this: https://i.sstatic.net/fX6Kx.png However, on mobile devices, it appears like this: https://i.sstatic.net/ilUZ9.png Below is the code sni ...

Expanding and Shrinking Panels through Touch in GWT

I have created a flexible panel using GWT and found inspiration from the following post, GWT resizable panel To see a demo of this in action, visit my hosting on AppEngine: I am seeking assistance in enabling touch events for resizing the Panel. I aim t ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

jQuery for Special Characters

I am currently facing an issue with the character &gt; in my jQuery datatable. Strangely, it displays '>' correctly but when I click on a row, the character &gt; appears and I am feeling frustrated. Is there any solution to this probl ...