Is there a way to keep a div element anchored at the top of the page until I reach the bottom and then have it stick to the bottom as I continue

I have a question that I hope is clear enough! On my webpage, there is a div at the top that I want to move to the bottom when I scroll and reach the end of the page. Hopefully, you understand what I'm trying to achieve!

If anyone has any ideas, I'm all ears ;)

Answer №1

To achieve the desired effect, consider utilizing the scroll event in conjunction with the animate() method. Using a flag named scroll will ensure that the div is only moved once:

var scroll = true;

$(document).on('scroll', function(){
    var my_div = $("#my-div");

    if(scroll){
       scroll=false;

       my_div.animate({
          top : $('body').height() - my_div.offset().top - my_div.outerHeight(),
       }, 1000);
    }
})

This approach should provide you with a helpful starting point.

var scroll = true;

$(document).on('scroll', function(){
  var my_div = $("#my-div");

  if(scroll){
    scroll=false;

    my_div.animate({
      top : $('body').height() - my_div.offset().top - my_div.outerHeight(),
    }, 1000);
  }
})
html, body { height: 500px; }

#my-div { 
  position: absolute;
  top: 0; 
  left: 0;
  width: 90%;
  height: 100px; 
  border: 1px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="my-div"></div>

Answer №2

If you want to trigger an event when a user reaches the bottom of a page and then smoothly transition the top property from 0 to match the height of the window minus the element's height, you can achieve this with some JavaScript code.

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() == $(document).height()) {
    $('div').css({
      top: $(window).height() - $('div').height()
    });
  }
});

Check out the demo on CodePen!

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 request to http://localhost:5000/error resulted in a 404 (Not Found) error message. I encountered difficulties connecting

When attempting to retrieve information about a product from Amazon using their productId with Express.js and ScraperAPI, an error is encountered: Error message: "{name: "RequestError", message: "Error: Invalid URI "${baseUrl}&url=https://www.amazon.com/d ...

Looking to center the numbers in my ordered list within a border box - any tips on how to achieve this?

I'm attempting to create a numbered order list with a circular border around it. The goal is to have the number of the list item centered within the circular border and the entire circle centered within the paragraph. Currently, both the number and th ...

Issues arise when trying to integrate iframes with Ionic and AngularJS, as they

Using iframes in my ionic app to display webpages within the application has presented a challenge. This is what I currently have implemented: <iframe class= 'webPage' name= "eventsPage" ng-src="{{object.url}}"></iframe> The issue ...

The <a> element does not direct to a different webpage

I designed a single-page layout with multiple sections and added links to the navigation bar for easy access. I also incorporated jQuery for smooth scrolling within the page. However, when I tried linking to other pages, it didn't work properly until ...

Experiencing issues with implementing shopping cart logic using KnockoutJS. Need help

The Objective Create a dynamic list of products. The Scenario Overview In my online shopping application, I want to showcase the products I add to my shopping list in a sidebar when I click the 'add button' for each product. Brief Problem Sum ...

Retrieve Next Element with XPath

I recently started working with XPATH and have a few questions about its capabilities and whether it can achieve what I need. The XML Document structure I am dealing with is as follows: <root> <top id="1"> <item id="1"> < ...

The HTML element does not expand to fill the entire page

I recently encountered a problem with my website. Everything was functioning smoothly until I decided to add some in-page links to a large page. After adding the links, the background no longer stretched the entire length of the page. When scrolling down, ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

Troubleshooting: Custom JQuery function not functioning as expected

I am currently facing an issue with the jQuery in my website while trying to implement a portfolio element. It seems to be related to the changePortfolio() function, but I am unsure of how to resolve it. $('.projects a[href^="#"]').on('clic ...

Using jQuery Validator Plugin to verify the existence of an email address

I've integrated the jQuery Validator Plugin into my newsletter form registration for validation purposes. Utilizing the remote validate method, I'm able to verify if an email address already exists in the database. The validation method is funct ...

Information derived from a provided URL

I am currently developing a Spotify stats app, and I am facing an issue with creating a context to store the token provided by the app in the URL when a user logs in. TokenContext.js: import React, { useEffect, useState } from "react"; // token ...

Testing the capabilities of AngularJS with e2e testing using the angular-recaptcha library

I have been attempting to e2e test my basic application, but I am facing challenges with the angular-recaptcha plugin from VividCortex (https://github.com/VividCortex/angular-recaptcha). Here is the test case I am working on: it('should redirect t ...

Ways to add elements to the DOM using jQuery from the local storage?

I'm facing a challenge where I have an input field and store the inputs in local storage. When I click on 'add', I want to immediately append the new inputs to my ul element. However, simply appending the current input won't work as it ...

Stop underscore templates from accessing global variables

I have a question about my underscore template. Here is the section of code in question: <% if (typeof title !== "undefined") { %> <p class="title"><%= title %></p> <% } %> Is there a way to avoid using the global scope ...

A collection of items that mysteriously affix themselves to the top of the page as

Unique Context In my webpage, I have a specific div element with the CSS property of overflow: auto. Within this scrolling div, there is structured content like this: <h3>Group A</h3> <ul> <li>Item 1</li> <li>I ...

Issue with authentication when accessing Google Video API

I'm attempting to utilize the Google API provided: I have downloaded the Sample Project and followed these steps: 1) Navigate to the Project Folder named API Video 2) Run npm install 3) Set GCLOUD_PROJECT = neorisvideo 4) Download Json from the C ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

Is it possible to prevent a webpage from being refreshed?

I need help with an HTML page that puts the worker on pause time which will be subtracted from his/her day job. The issue is that when he/she refreshes the page, the timer starts from the beginning automatically. I want it to continue without resetting. Is ...

Encountered an issue when deploying a Gatsby JS site on Netlify due to a non-zero exit code returned by the build script

Recently, I discovered Gatsby JS (https://github.com/gatsbyjs/gatsby) and chose to construct my portfolio website using this generator. To begin, I forked their default starter site (gatsby-starter-default) and developed my portfolio from there (https://g ...

What is the best way to pass a variable and its corresponding state-updating function as a prop in a React component?

Considering I have a variable defined as follows: const [APIKey, setAPIKey] = useState([]) Is it possible to group these together into a single variable and then pass it as a prop? const passAPI = {APIKey, setAPIKey} Here is my approach to passing it alo ...