Tips on preventing the fixed position from scrolling at the footer

Despite extensive research, I am still unable to understand why this particular issue is not resolving for me.

The problem lies within two specific div elements that are causing trouble. One of the divs is utilizing position: fixed in order to remain visible on the screen at all times.

The intention is for this div to stop being fixed once it reaches the footer and instead stick to the top of the footer. Although I attempted to implement solutions from this reference, the div consistently jumps back up to the top of the page upon reaching the footer.

For demonstration purposes, here is a fiddle:

$(document).scroll(function (){
  if($('.userInfo').offset().top + $('.userInfo').height() >= $('footer').offset().top - 10){
    $('.userInfo').css('position', 'absolute');
  }
        
  if($(document).scrollTop() + window.innerHeight < $('footer').offset().top){
    $('.userInfo').css('position', 'fixed');
  } 
});
.profileMain{
    display: flex;
}

.userInfoContainer{
    height: 100%;
    width: 50%;
    display: inline-block;
}

.userInfo{
    background: red;
    width: 50%;
    position: fixed;
}

.userContent{
    background: blue;
    width: 50%;
    margin-bottom: 10em;
}

footer{
  background: gray;
  width: 100%;
  height: 30em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class = "profileMain">
  <div class = "userInfoContainer">
    <div class = "userInfo">f</div>
  </div>
  <div class = "userContent">f</div>
</div>

<footer></footer>

I am seeking assistance in understanding where I may be going wrong in my approach. Any guidance would be greatly appreciated.

Answer №1

To achieve the opposite effect of the example given (keeping the div at the top instead of the bottom), simply remove the window.innerHeight from the second if statement. Instead, compare the scroll position plus the element's height with the footer's offset using offset. Utilize both the top and bottom properties to position the div where desired.

This code snippet should help you accomplish this:

$(document).scroll(function() {
  if ($('.userInfo').offset().top + $('.userInfo').height() >= $('footer').offset().top - 10)
    $('.userInfo').css({
      'position': 'absolute',
      'bottom': 0,
      'top': 'auto'
    });

  if ($(document).scrollTop() + $('.userInfo').height() < $('footer').offset().top)
    $('.userInfo').css({
      'position': 'fixed',
      'top': 0,
      'bottom': 'auto'
    }); // revert when scrolling up
});

Here is a fiddle showcasing the implementation: https://jsfiddle.net/xpvt214o/93144/

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

Tips for replacing all occurrences of a specific string in HTML while preserving JavaScript attributes

Is there a way to use RegEx to replace part of an HTML document without affecting the root element or other elements like event listeners? Consider this scenario: for (; document.body.innerHTML.indexOf(/ea/) != -1;) { document.body.innerHTML = docu ...

Using Python in Django to seamlessly add products to the shopping cart

Seeking guidance in creating a simple function that can capture the product ID and insert it into the user's shopping cart upon clicking the "add to cart" button. I have already set up the shopping cart table and the product table but am struggling to ...

Is it possible to stack divs horizontally in a liquid layout while allowing one of the widths to be dynamic?

This is the code snippet and fiddle I am working with: http://jsfiddle.net/hehUt/2/ <div class="one"></div> <div class="two">text here text here text here text here text here text here text here text here text here text here text here te ...

What is the best way to horizontally center a div that doesn't have a set width

I am a beginner in CSS and have been experimenting with various solutions from Stack Overflow, but so far none of them seem to be working for my specific case. Below is the parent div code from an existing application where I cannot control the inline sty ...

Implementing a PHP/HTML caching system is a crucial step in optimizing website

Having delved into various guides about implementing a PHP cache system for my custom-coded, query-heavy, and expanding site, one resource I found useful is this one: While I grasp the concept, there are specific parts of my page that cannot be cached. Wh ...

Transforming the FormData() format into a jQuery structure

Hey there! I've been doing some research online about uploading files using JavaScript, and I stumbled upon some great resources, including this one https://developer.mozilla.org/en-US/docs/Web/API/FormData. I have a script that uploads an image to th ...

CSS cascading not happening

Within the usersettings.css.erb file, line numbers are provided for easier reference. 11 #userSettingMain .form-horizontal .controls { 12 13 margin-left: 30px; 14 } 15 16 #user_birthday_3i{ 17 18 margin-left: 0px; 19 } U ...

Unlock the Power of Vue Draggable in Vue.js 3 with These Simple Steps

When attempting to implement Draggable in Vue.js 3, I encountered an error message: VueCompilerError: v-slot can only be used on components or <template> tags. Below is a snippet of my code: <draggable tag="transiton-group" name="s ...

Creating a cookie on click event to change the background

I am working on changing the background of a div onclick and storing it with a cookie. However, I am facing some issues with my code. I can't determine if the cookie has been properly set, and I am unsure about changing the background with the value o ...

How can the hreflang tag be used correctly in a React application that supports multiple languages?

I have a React application with 3 pages(routes) and I support 2 languages (English and Spanish). Should I insert the following code into the <head></head> section of the public\index.html file like this? <link rel="alternate" ...

Ways to conceal specific content within a text using CSS

Help me with the updated code <html> <title>css</title> <head> <style> #st { z-index: -114; margin-right: -80px; } </style> </head> State Code : <span><span id="st"></span>Maharashtra - MH ...

Exploring the Link Between jQuery and HTML

Is it possible to connect between an HTML file and a jQuery file? Here is an example scenario: jquery-test.js: $(document).ready(function(){ $('#inputForm').submit(function(){ $('#inputForm :text:not("#submit")').each(func ...

Achieve a responsive layout by dynamically sizing child div elements to fill their parent container using percentage-based margins and

I'm having trouble getting the child divs to stretch to the parent, and I'm not sure if I need to specify a % width on #fullpage-content even though #middle is set to 76%. I seem to have forgotten... Would you like to check out this link where c ...

How can I modify cell padding using a media query for a specific screen resolution?

In the desktop view, which is larger than 480px, I need a specific <td> to have a left-padding of 9px. However, once the resolution goes below 480px, this left-padding should increase to 18px. At the moment, my padding definition is specified within ...

Latest output is fetched by jQuery from the load() method

I'm encountering an issue with the code present in index.html: $(document).ready(function() { $('#generate').click(function() { //$("#results").empty(); $("#results").html(""); $("#results").load("generate.php"); }); }); In addition ...

Selecting multiple values using Ajax in a select2 dropdown menu

I am currently using Select2 and fetching data in JSON format via AJAX. View: <select class="form-control qual_id" multiple> <option value="">-Select Degree-</option> <option value="1">SSC</option> <option val ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

Executing JavaScript code upon clicking a menu item involves creating event listeners for each menu

Currently, I am working on a Squarespace website that includes a navigation bar. I am looking to incorporate a JavaScript code as a link within the navigation bar. The specific JavaScript code is as follows: <div> <script type="text/javascript ...

Exploring the functionality of $.param in jQuery

After extensive research online, I found that the most helpful information was on the official jQuery site. Here is the code snippet I am currently using: var param = { branch_id : branch_id}; var str = $.param(param); alert(str); However, when I log or ...

Different methods to retrieve content within a div that is located on a separate, included page

It's a bit tricky to come up with a title for this topic, but essentially, I'm trying to figure out how to get content from an included page into a specific div using HTML and PHP. Let me break it down: In the header.php file, we have the follo ...