"Keep the div locked to the screen when the bottom of the div aligns with the

Hey everyone! I'm currently grappling with a project that requires me to keep a div stuck to the screen (prevent scrolling) when its bottom reaches the bottom of the screen. I have two divs on the page, both with varying heights. My aim is to keep div2 stuck while allowing div1 to scroll.

<script>
  var divheight
  var scrolltop
  var screenheight
  if(divheight-scrolltop <= screenheight){ 
  /* I need to find a way to keep the div in place without using fixed positioning, as both divs are floating. */ } 
   else { /* Release the div */ }
 </script>

I'm stuck on what to include in the if and else conditions. Any help would be greatly appreciated!

Answer №1

Implement a function that triggers when the user scrolls. The purpose of this function is to calculate the difference between the screen height and the bottom of a specific div. If this difference is equal to or less than zero, then change the CSS position to fixed. This technique can be very useful for enhancing the user experience.

(function ($) {
  $('.myDiv').scroll(function () {
    var $this = $(this),
        windowHeight = $(window).height(),
        divHeight = $this.height(),
        divBottom = $this.offset().top + divHeight;
    if (windowHeight - divBottom <= 0) {
        $this.css({
            'position': 'fixed',
            'bottom': '0'
        })
    }
  });
})(jQuery);

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

Leveraging TypeScript's declaration file

Greetings! I am currently facing an issue while utilizing a declaration file in my TypeScript project. Here is the declaration file that I am working with: // Type definitions for Dropzone 4.3.0 // Project: http://www.dropzonejs.com/ // Definitions ...

Problem integrating multer with Express JS and Node JS

Click here to access the server.js file on GitHub Following a tutorial, I have implemented code accordingly. However, when working with an updated version of Express JS, errors are being thrown on the side of Express JS. Error C:\nodefiles&bso ...

Having trouble fetching values in Node.js after a certain period of time has passed

Whenever the page loads, the sha1 function is supposed to run and it should run after 5 seconds. var crypto = require('crypto'); console.log(sha1()); setTimeout(sha1, 5000); console.log(sha1()); function sha1() { var dt = dateTime.create(); ...

Looking for a JavaScript function that will enable the acceptance of commas and spaces

How can I modify this integer validation function to allow for commas and spaces to be entered during the keydown event? function intValidate(event) { if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || even ...

Is it possible to incorporate a PHP if-else statement in the action attribute of an HTML form?

I'm currently developing a form to allow users to create a login username and password. Once the account creation is successful, I want the user to be directed to the actual LOGIN form. To manage this process, I've implemented various checks usi ...

What is the best way to ensure a jQuery UI slider recognizes when the mouse is released after being clicked?

I have integrated the jQuery slider into my application and am facing an issue with triggering an event to update the database upon releasing the slider. Currently, I am using the following code snippet: $('.ui-slider-handle').mouseup(function () ...

personalized styles based on user preferences

My website features a gaming section where users can view quick status updates of their stats using colors like blue, red, and green. I am looking to generate something similar for each user. Here is what I have so far: <style> .box2 { height: ...

Adjust the size of a Highcharts chart before printing

I'm facing an issue with a chart that doesn't have a specified height or width. My goal is to print the graph in a taller and larger size when I click on the print button. I attempted to use setSize() function, but since there are no original di ...

Retrieve the data stored in an array of objects

code props.thumbnails.forEach(value=>{ console.log(value.photo.thumbnail_url); }) error TypeError: Cannot read property 'thumbnail_url' of undefined Trying to loop through props.thumbnails array and access the thumbnail_url pro ...

Encountering a Uncaught TypeError when attempting to split an undefined property, but issue is limited to certain pages

Recently, I've encountered an issue with iziModal on specific pages where I'm getting an error message. The error I'm facing is: Uncaught TypeError: Cannot read property 'split' of undefined at r.fn.init.t.fn.(anonymous fu ...

Enhancing an array item with Vuex

Is there a way to change an object within an array using Vuex? I attempted the following approach, but it was unsuccessful: const state = { categories: [] }; // mutations: [mutationType.UPDATE_CATEGORY] (state, id, category) { const record = state. ...

Learn how to trigger the keydown function in VUE programming

I am trying to create a method that will be triggered whenever any key on the keyboard is pressed, regardless of where the focus is. I want to be able to determine which key was pressed in this method. Currently, I have set up an event listener for keydow ...

Create a dedicated jQuery mobile login page in a separate HTML file

I am creating a hybrid app using JQM v1.4. The initial page is the login page and users must log in to access the content pages. Therefore, I plan to separate the HTML pages as follows: - Login page on its own, and all other content pages will be combine ...

the three.js code runs smoothly on JSfiddle, but it does not seem to be working properly

Check out this basic three.js code snippet for generating custom geometry http://jsfiddle.net/67Lgzjpb/. After attempting to run this code directly in my browser (not via JSFiddle), an error message pops up: TypeError: geom.computeCentroids is not a funct ...

Displaying data on the user interface in Angular by populating it with information from the form inputs

I am working on a project where I need to display data on the screen based on user input received via radio buttons, and apply specific conditions. Additionally, I require assistance in retrieving the id of an object when the name attribute is chosen from ...

Load the page's content gradually, without needing to wait for all the content to be fully loaded

I am facing an issue with a webpage that displays 10 different items, each of which has a slow loading time. Currently, the entire page waits for all 10 items to fully load before displaying anything. I am interested in finding out if it is feasible to sh ...

Issue with model not triggering delete request upon destruction

sil is the deletion event, however it does not trigger the delete request method. var NoteModel = Backbone.Model.extend({ urlRoot:"/DenemeBackbone/webresources/com.mycompany.denemebackbone.note", defaults: { note: "Empty" } }); I am w ...

Guide on how to align multiple divs at the center of a container using CSS

Experimenting with centering a divider in the style of Windows metro. .container { height: 300px; width: 70%; background: #EEE; margin: 10px auto; position: relative; } .block { background: green; height: 100px; width: 10 ...

What is the best way to activate a click event when I set a radio button to checked?

I am facing an issue with an uninitialized property in my app.component.ts: color!:string; I am trying to automatically initialize the color property when a radio button is selected: <div> <input type="radio" name="colors" ( ...

Trigger a jQuery click event when reaching a specific viewport width

Is there a way to automatically unroll a drop-down menu when the viewport width goes below 640? I've tried using jQuery to trigger a click event, but so far, it hasn't been successful. Any suggestions on how to make this work? if($(document).wid ...