Release a stationary element upon scrolling down the page

I have a calculator feature on my website which was coded in php. At the end of this calculator, there is a section that displays the results.

While the results div works properly on desktop, I am looking to implement a fix for mobile devices. Specifically, I want the results div to be fixed at the bottom until the user scrolls back to its original position on the page. Once they reach the original position of the div, I would like it to become static again.

In simpler terms, there is an element on the page that stays fixed to the bottom initially, but becomes unstuck once the user scrolls back up to where it originally was.

To better illustrate what I'm trying to achieve, you can view an example page. Make sure to take a look at the MOBILE version!

Could anyone please advise me on how to accomplish this?

Thank you in advance!

Answer №1

Below is the method I have used in the past:

  1. Determine the original position of the bottom of the element.
  2. Calculate the height of the viewport.
  3. Subtract the viewport height from the original bottom position to find the scroll position needed for the entire element to be visible.
  4. Add a scroll listener to the window to monitor the scroll position and apply or remove the fixed class accordingly.

For example:

// Get the document element for later use.
var doc = document.documentElement;

// Retrieve the important message element.
var importantMsg = document.getElementById('important-msg');

// Find the distance between the bottom of the message and the top of the page without it being fixed.
var originalMsgBottom = importantMsg.getBoundingClientRect().bottom;

// Obtain the window's height.
var windowHeight = Math.max(doc.clientHeight, window.innerHeight || 0);

// Determine the scroll position to be tracked while scrolling.
var scrollPosition = originalMsgBottom - windowHeight;

// Set the message as fixed by default.
importantMsg.className = 'important-msg-fixed';

// Create a function to check the current scroll position against the previously defined position.
var scrollFunction = function() {
var scrollTop = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
  if (scrollTop >= scrollPosition) {
    importantMsg.className = ''; // If met, remove the fixed class.
  } else {
    importantMsg.className = 'important-msg-fixed'; // If not, add it.
  }
}

// Have our function run every time the window scrolls.
window.addEventListener('scroll', scrollFunction);
#important-msg {
  background: #f00;
  color: #fff;
  padding: 10px;
}
.important-msg-fixed {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  margin: 0;
}
<h1>Lorem Ipsum</h1>
<p>Scroll Down</p>
<p>Scroll Down</p>
...
<p id="important-msg">Important Message</p>
<p>More Stuff</p>

Answer №2

If you couldn't care less about IE browsers (or if you happen to stumble upon this in the year 2022 :D)
you have the option to utilize position: sticky

.sticky{
  position: sticky;
  bottom: 0;
  background: red;
}
<div class="content">
  <p style="border:4px dashed;height:150vh;">Keep scrolling</p>
  <div class="sticky">I'M STICKY</div>
</div>

<div class="content">
  <p style="border:4px dashed;height:150vh;">Scroll back up</p>
</div>

For further compatibility information, visit here: https://caniuse.com/#feat=css-sticky

In case you desire a (sort of?) substitute you may consider:

.sticky{
  position: absolute; /* falls back to absolute */
  width: 100%;        /* fallback width */
  position: sticky;
  bottom: 0;
  background: red;
}

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

Creating a responsive navbar with a custom width form

Just started working with bootstrap and playing around with some new UI concepts. I'm having an issue with a non-responsive form width within my navbar, even though the navbar itself is responsive. I've tried using different collapse classes, but ...

Encountering an "invalid query parameter" error when making a find request with FeatherJS and ReactJS

Adding $show:true to the data below results in an error when making the find request. However, when I remove $show:true, everything works perfectly with no errors. The error message states: Invalid query parameter $show. I have attempted using differe ...

Exploring the differences between two CSS style attributes using JQuery

Can someone help me with a quick question about CSS? I need to compare two style attributes, specifically margin-left. If the margin-left is less than 500px, I don't want to make any changes. However, if it's greater than 500px, I want to add ano ...

Applying Regular Expressions in Java to "convert" a CSS style into an HTML tag style

In my Java code, I have a String variable that contains HTML code like this: <span style="text-decoration: underline;">test</span> My goal is to convert it to look like this: <u>test</u> If the HTML code is like this: <span ...

When using AJAX, make sure it doesn't overwrite the global variable for JQUERY

$.each(data, function (index, info) { var a = info.notes; var b = info.permission; //var c = null; var c = null; $.ajax({ url: "asse ...

The Media Queries in the Wordpress html5blank theme are failing to function properly

While using the html5blank theme to develop a WordPress site, I noticed that my media queries are functioning properly locally. However, when I add them to the WordPress style.css file, they seem to stop working. Even after stripping away all other media q ...

Creating an HTTP request inside an Export Function in a MEANJS application

Initially, I utilized the Yo MeanJs generator to kickstart my project. As a newcomer in the world of MeanJs, things are starting to look quite complex for me. Currently, my MeanJs application is supposed to retrieve data from an HTTP request but, unfortun ...

Encountering a problem during the installation of the udev module in a Node.js

When I run the command below: npm install udev I encounter the following error message: npm WARN enoent ENOENT: no such file or directory, open '/home/mitesh/package.json' npm WARN mitesh No description npm WARN mitesh No repository field. ...

Using jQuery UI to make elements sortable and draggable, while also retrieving the index of the dragged element

I encountered a specific issue while using jQuery UI sortable and draggable simultaneously. My goal is to determine the index or placement of the newly dragged element within the list. I am able to accomplish this when rearranging elements within the list. ...

Tips for building forms with VUE?

Today is my first attempt at learning VUE, and I've decided to follow a tutorial on YouTube from freeCodeCamp.org. The tutorial covers the concept of components in VUE, specifically focusing on creating a login form project. Despite following the ins ...

Verify the status of the mongodb server synchronously

Is there a method to detect if a mongod instance is still operational while using mongoclient? In my mongoclient module, I have implemented a db.on('close') handler which functions properly when mongod exits normally. However, if the server proc ...

Tips for managing a multi-page website with AngularJS

Currently, I am embarking on the development of an Android application using Cordova. To interact with the service end-point of a Drupal website, I have opted to utilize AngularJS for data fetching and manipulation. Initially, my attempt to incorporate ngR ...

developing authentication codes using javascript

Currently, I am working on developing a sign-up system that allows users to easily generate a random string with the click of a button. The generated string can then be shared with non-users who wish to sign up. The new user will need to enter their chose ...

What is the use of the typeof operator for arrays of objects in TypeScript?

How can I update the any with the shape of the options's object below? interface selectComponentProps { options: { label: string; value: string; }[]; } const SelectComponent: React.FC<selectComponentProps> = ({ options, }) => ...

Display HTML content within a Material-UI Card component using React

Currently, I am utilizing the < CardHeader /> component nested within a < Card />. <CardHeader title={card.title} subheader={`${moment(card.createdAt).startOf('minute').fromNow()}` + ' by ' + <div>ABC</div>}/ ...

The scrollHeight property for a textarea element that is set as

Currently, I am working on enhancing a form results page by implementing a readonly textarea to showcase the submitted email address. My main goal is to allow the textarea to dynamically adjust its height in order to display the full email instead of trunc ...

Tips for adding a class to the end of the DOM class

Greetings! I'm currently working with the code below: for ( let x: number = 0; x < this._vcr.element.nativeElement.querySelectorAll(".ui-steps-item").length; x++) { let className: any = this._vcr.element.nativeElement.querySelectorAll( ...

Looking to automate the selection of a dropdown menu using Selenium with JavaScript

Below is the code snippet for a drop-down: <div class="w-1/2 px-8 pt-6"> <div class="Styled__FieldWrapper-sc-1fqfnqk-1 bQZNMa mb-6"> <label class="form-label" for="transfer.account">Transfer Acc ...

Move the DIV element to the bottom of the webpage

On my website, I have implemented a countdown timer and a responsive wallpaper. My goal now is to center the div at the bottom of the page and make sure it always stays there. I've tried some code snippets from StackOverflow, but they either gave me a ...

The MediaSource API is not supported on Chrome 27

My current browser version is Chrome 27, and based on this source, it is indicated that the MediaSource API comes pre-installed. However, upon further examination on the same page, the test section states that Your browser does not support the MediaSource ...