"Ensure div remains at the bottom of the page even while

In order to implement a feature where the menu sticks to the top when scrolling down, you can use the following JS code. You can view a live example of this functionality on this Plunker by widening the preview window to see the columns side by side.

window.addEventListener("scroll", handleScroll);

function handleScroll() {
  const $panel = $(".menu")[0];
  if ($(this).scrollTop() > 90) {
    $panel.classList.add("sticky");
  } else {
    $panel.classList.remove("sticky");
  }
}
.navbar {
  background-color: #fff;
  border-bottom: 1px solid;
  font-size: 48px;
  line-height: 48px;
  position: fixed;
}

.contents {
  margin-top: 55px;
}

.menu.sticky {
  bottom: 60px;
  right: 0;
  position: fixed;
  top: 55px;
  width: 31.491712707182323%;
}

.menu.sticky .tab-content {
  overflow: auto;
}

.menu .tab-content {
  padding: 20px;
}

.menu button {
  margin-top: 20px;
}

.btn.pull-right {
  margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navbar navbar-fixed-top">NAVBAR</div>
<div class="contents">
...
...
<ul>
            ...
           </ul>
        </div>
      </div>
    </div>
</div>

If you want the content of the active tab in the sticky menu to be scrollable with the bottom aligning with the visible window, you can refer to these images for reference:

https://i.sstatic.net/rwNxP.png

As you continue scrolling, the scrollable area in the tab should end up matching the parent's bottom as shown here:

https://i.sstatic.net/lcetO.png

To achieve this effect, you need to make the tab content scrollable and adjust the JavaScript accordingly to ensure the menu is positioned correctly at the bottom.

Answer №1

To calculate the value of scrollBottom, follow this formula:

$( document ).height() - ( $( window ).scrollTop() + $( window ).height() )

Next, compare this value with the desired bottom margin, which in this case is the .outerHeight() of the footer:

// Calculate height including margin and padding of footer
var h = $("footer").outerHeight(true);

$(window).scroll(function() {

  // Get scrollBottom value
  var scrollBottom = $( document ).height() - ($(window).scrollTop() + $(window).height());

  if (scrollBottom >= h) {
    $(".box").css('bottom','0');
  }

  // Adjust position when scrolling with footer
  if (scrollBottom < h) {
    $(".box").css('bottom', (h-scrollBottom) + 'px');
  }
  
  // Show/hide sidebar
  if($(window).scrollTop() > 200){
    $(".box").css('opacity', '1');
  }

  if ($(window).scrollTop() <= 200) {
    $(".box").css('opacity', '0');
  }
  
});

body{
  margin:0;
  padding:0;
}
.box{
  background:#f00;
  height:100px;
  width:100px;
  position:fixed;
  bottom:0;
  right:0;
  opacity:0;
}
.foo{
  height:600px;
  border:1px solid #000;
}
footer{
  background:#333;
  color:#ccc;
  height:150px;
  padding:20px;
  margin:10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js">
</script>
<div class="box">
</div>
<div id="all">
  <div class="foo">Text</div>
  <div class="foo">Text</div>
  <div class="foo">Text</div>
  <div class="foo">Text</div>
  <div class="foo">Text</div>
</div>
<footer>
    I am a footer
</footer>

Answer №2

To start, consider eliminating the javascript and using CSS instead

position: sticky

This method is widely supported across all browsers. Additionally, there are polyfills available for added support.

Take a look at this demonstration:

You may need to adjust the window size to fully experience the effects in action (such as the sidebar sticking to the top, reaching the end of the page, and automatically scrolling).

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

The previous and next buttons are displaying side by side rather than being positioned at the outer edges

I am having an issue where the prev and next buttons are displaying next to each other instead of at the edge of the div. Can someone please assist me in fixing this problem? Below is the provided HTML code: <div id ="moreOption_80322271" class="m ...

Is there a versatile Node.js HTTP request module that is compatible with both server-side and browser-side development, particularly when packaged with Webpack?

Currently, I am searching for a request module that can operate seamlessly in both the Node.js server and the client when compiled with Webpack. The requirements are quite straightforward. I simply need to execute some basic HTTP Ajax requests such as get ...

Is it possible to adjust the height of the navbar in Bootstrap?

Currently, I am in the process of replicating the mac OS navbar and am seeking guidance on resizing the navbar height and adjusting text size to around 12px. This is my first time working with bootstrap, so any assistance would be greatly appreciated. Addi ...

Can you identify any issues with this Javascript code's "If" condition?

In my JavaScript code, I have an "if condition" that looks like this: for (var i in data) { //Gender.push("Gender " + data[i].JenisKelaminID); if (data[i].JenisKelaminID == 1) { Gender.push("Men"); } if (data[i].JenisKelaminID == 2) { Gend ...

A set of four responsive divs arranged vertically

Confession time... I'm facing a challenge with this task... I'm attempting to create a responsive page with 4 stacked divs. Here are the guidelines for each div: The header div: The text should be at the bottom, serving as a slogan placed clo ...

In order to enhance your programming skills, avoid hard coding functions and ensure that data is returned after binding changes

I am trying to create a method where I can provide a DOM as a parameter and retrieve data from image_preview. The goal is to make image_preview reusable instead of hardcoding it inside the function. Additionally, I want to separate image_preview.model() an ...

Arranging HTML elements with jQuery - the existing script flips back and forth

I have created a code snippet on CodePen that showcases a feature of the website I am currently developing: http://codepen.io/barrychapman/pen/BzJGbg?editors=1010 Upon loading the page, you will notice 6 boxes. The first box is active, while the remaining ...

PHP session does not update when using AJAX

I have been on the hunt for a solution to this issue. My website features lengthy video files, and I don't want users to be timed out while watching them. To prevent timeouts, I attempted to use an AJAX call on a timer to refresh the session. Despite ...

Pause the jquery script when a key is pressed

Currently, I have a script that loads a php file within a div and automatically refreshes every 5 seconds. Check out the code below: $("#load_timeout").load("time_out.php"); var refreshId = setInterval(function() { $("#load_timeout").load('time_o ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

Adjusting the dimensions of a tri-fiber canvas prior to saving it

I have a unique inquiry regarding Three Fiber. Once the download button is clicked, it generates a base64 using toDataURL, which can then be downloaded. The resulting image adopts the height and width of the canvas, which in turn matches the height and w ...

Error: The function res.getHeader is not recognized within the Next.js API environment

I am currently working on a web application using NextJS 13, TypeScript, Next Auth v4, Prisma (using SQLite for development), and OpenAI. While accessing the API endpoint, I encountered an error in the console with the following message: error - TypeError ...

In which location are HTML files stored within WordPress plugins?

Can someone help me locate the HTML files within WordPress plugins? I'm looking to make edits to the HTML and CSS files of a plugin, but I can't seem to find the specific HTML file. Any guidance on where these files are stored would be greatly ap ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...

Creating colorful containers using Bootstrap

Hey there, I am interested in creating small colored boxes to represent different meanings for each color. I came across this code snippet but I am unsure how to adjust the size: <div class="p-3 mb-2 bg-primary text-white">.bg-primary</d ...

Attempting to extract the data from SweetAlert

I've been attempting to retrieve the return value from sweetalert, but I encountered this: Promise {<pending>} >__proto_:Promise [[PromiseStatus]]: "resolved" [[PromiseValue]]:true resulting from this piece of code: var ret = swal({ ...

Steps for showing an error prompt when input is invalid:

In my Vue 3 application, I have implemented a simple calculator that divides a dividend by a divisor and displays the quotient and remainder. Users can adjust any of the four numbers to perform different calculations. <div id="app"> <inp ...

Steps to apply V-model to elements

I am currently facing an issue with giving dynamically created input fields dynamic v-models from JSON data using vue.js. Here's what I'm doing: new Vue({ el: '#app', data() { return { totalAmt: 500, paymentMode: ...

What steps should I take to ensure that pull is functioning correctly with mongoose and mongodb?

I am facing an issue while trying to retrieve an object from an array within a Model. Despite verifying my query params and confirming that they are correct, I am unable to get it to function as expected. Any assistance on this matter would be highly appre ...

jQuery DataTables covering a CSS-anchored menu bar

My webpage has a pinned navigation menu bar at the top and some tables with interactive features using jQuery's DataTables. However, after implementing jQuery, I encountered an issue where the tables cover the menu when scrolling down, making it uncli ...