Keep elements in position when their bottom edge becomes visible while scrolling

This task may appear intricate, but I will do my best to explain it!

I want to create a continuous scrolling article display similar to Bloomberg Politics (), but with a slight twist.

My idea is to have the current article's bottom edge stick to the bottom of the viewport and let the next article scroll in over the top, instead of having static articles until they are scrolled away.

I've made an attempt on jsfiddle to showcase what I mean and where I currently stand...

<div class="wrapper">
    <article class="article article--one">
        Text text text text text text text text text
    </article>
    <article class="article article--two">
        Text text text text text text text text text
    </article>
</div>
.wrapper {
    padding: 8px;
    position: relative;
}

.article {
    width: calc(100% - 48px);
    min-height: 1200px;
    background: #ddd;
    padding: 24px;
}

.article--two {
    background: #f5f5f5;
}

.scroll {
    position: relative !important;
    top: auto !important;
    margin-top: 1248px !important;
    float: left !important;
    left: 0 !important;
    right: 0 !important;
}
$(window).scroll( function() {    
    $('.article').each( function(i) {    
        var bottom_of_object = $(this).position().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();
        var height = $(this).outerHeight();
        var secondheight = $('.article--two').outerHeight();
        var down = bottom_of_object;

        if (bottom_of_window > bottom_of_object) {     
            $(this).css({
                'position': 'fixed',
                'bottom': '0',
                'left': '16px',
                'right': '16px'
            });
            $('.article--two').addClass('scroll');    
        }    
    });     
});

JsFiddle

If you find this confusing, feel free to ask any questions!

Cheers!

Answer №1

This solution may not be fully optimised and is not the best for mobile devices, but it gets the job done.

$window = $(window).on('scroll', function () {
    var scroll = $window.scrollTop() + $window.height();
    
    $('li').each(function (i) {
       var $el = $(this),
           offset = scroll - $el.offset().top - $el.height();
       $el.children().css('top', offset>0 ? offset : 0);
    });
});
body {
  margin: 0;
}
ul {
  position: relative;
  display: block;
  text-align: center;
  counter-reset: page;
  padding: 0;
  margin: 0;
}
li {
  height: 150vh;
  list-style: none;
  background: green;
  position: relative;
  margin: 0;
  padding: 0;
}
li:nth-child(even) {
  background: blue;
}
article {
  position: relative;
  height: 100%;
  width: 100%;
  background: inherit;
}
article:before {
  counter-increment: page;
  content: "Page " counter(page);
  font-size: 1.6em;
  color: white;
  top: 50%;
  margin-top: -0.5em;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <article></article>
  </li>
  <li>
    <article></article>
  </li>
  <li>
    <article></article>
  </li>
</ul>

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

Looking for a way to locate any elements in jQuery that do not contain a certain CSS class?

I am looking to target all form elements that do not contain a specific CSS class. For example: <form> <div> <input type="text" class="good"/> <input type="text" class="good"/> <input type="text" class="bad"/> ...

retrieval: unspecified information obtained through body parsing (Node.js Express)

Having just started working with React.js and Node.js, I encountered a simple issue that I can't seem to solve. I am using the lightweight fetch API to post data and trying to receive that data using body-parser, but it always returns undefined. impo ...

Hey there, I'm looking to automatically delete new users from my mongoDB atlas database if they haven't verified their phone number within 2 minutes. I believe using the TTL feature would be

Database Schema In my User schema, the field isVerified is initially saved as false. The user enters their phone number, receives a verification token via SMS, and both the token and number are saved in the database. Once the user enters the verification ...

What is the best approach for promoting reusability in Angular: creating a new CSS class or a new component?

I have a div with a set of CSS properties that are essential to my application. These properties will be reused across multiple pages and components. <div style="display: flex; flex-direction: column; height: 100%"> //inner html will vary based on c ...

Error: Preflight request returned a 405 HTTP status code when querying Ionic + CI backend

I am currently working on my first app using ionic with a codeigniter backend. However, I am encountering the "Response for preflight has invalid HTTP status code 405" issue in ionic + CI backend. Can anyone help me solve this problem? This is my controll ...

Error Loading JQuery: The function $() is not recognized in the Shopify platform

I seem to be overlooking something obvious. I am using Shopify and have included jQuery in the head section of the theme.liquid file: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> This script is placed rig ...

The Ajax form is failing to send any headers

Whenever I submit my form, the header data doesn't seem to be coming through. Even though I've done this type of submission numerous times (figuratively speaking), there's always a chance that I might be overlooking something. Any ideas? Che ...

Initiating Ajax to trigger the body's onLoad event

Whenever I use an ajax call to load a div, the entire page refreshes. It seems that the 'body onload=init()' event is triggered on ajax response causing all the initialization to repeat, which is not desired. Is there a way to only load the div t ...

What is the best way to retrieve a lengthy HTML page string parameter from a Java request?

While working with Javascript, I encountered an issue with sending HTML pages in post data. In my Java code, I used String html = request.getParameter("templateHtml"); and during debugging, I could see the HTML string in the request. However, the "html" va ...

The use of Material-UI collapse animation in a table results in the insertion of div elements, triggering a validateDOMNesting warning

Having a data-filled table, I am looking to implement smooth transitions when adding or deleting an item. This is a ReactJS project utilizing Material-UI. The desired effect is similar to the one demonstrated in their example. While they use a List compon ...

Adding the victory chart in react-native slider causes performance issues, as the slider becomes laggy and there is a delayed reflection

When I use a slider in my application without including a Victory chart, the slider functions smoothly with no issues. However, integrating the slider with the Victory chart causes lag and delays in updating the state value on screen. For more detailed in ...

What is the procedure for extracting data from a JSON file within an HTML document?

Hey there, I am currently working on reading data from a json file using ajax. I have created a Video object that consists of Courses objects with titles and URLs. However, when attempting to read the title and URL of HTML as an example, I am not seeing a ...

When attempting to pass data to a modal, an error occurs due to props being undefined. This results in a TypeError with the message "Cannot

I'm working on a product listing feature where each item displays some information along with a "more details" button. When the button is clicked, a modal window opens to show additional details of the specific product (using props to pass data betwee ...

How to import a dynamic typescript file in Next JS

As per the NextJs documentation, dynamic import can be used for JavaScript files like const DynamicComponent = dynamic(() => import('../components/hello')). Is it also advisable to use dynamic imports for .tsx files in a similar manner? ...

Convert image buffer to string using Mongoose getter?

I have developed a basic node backend application modeled after eBay. I am now working on creating a react frontend app to complement it. Within the app, users can list items for sale and include a photo with their listing. The item information is stored ...

The jQuery load() callback triggering a POST request unexpectedly instead of a GET request

Utilizing jQuery's load() method, I am attempting to insert a page fragment into a new page. It appears that this can only be achieved with load(), as get() does not support page fragments. Upon completion of the load, it is necessary for me to invok ...

Is there a way for me to establish a maximum word count for a paragraph?

When my paragraphs get lengthy, I only want the first 30 words to display on two lines. Is there a way to achieve this using HTML, CSS, or JS? The code snippet I tried did not work as expected. .long-text{ width: 70ch; overflow: hidden; white-sp ...

Unleashing the power of Vuex with promise chaining

One challenge I am facing is making API calls to retrieve an array of endpoints, which are then used to fetch data from another API. // Raise isLoading flag this.$store.commit('isLoading', true); // Initial data fetch this.$s ...

Video tag with centered image

For a current project, I am in need of rendering a centered image (a play button) at runtime on top of a video based on the UserAgent. If the userAgent is not Firefox, I want to display the image as Firefox has its own playEvent and button on top of the vi ...

Enhance dynamically generated HTML using jQuery Mobile

Using jQuery Mobile version 1.2.0 I am dynamically generating HTML using JavaScript ($(selector).html(content)), adding it to the DOM, and then displaying it ($.mobile.changePage()). After that, I make an AJAX call, retrieve some data, and re-generate th ...