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

Tips for including HTML in a JSON request in ReactJS

Upon sending the request as shown below, the response was successfully received. { "contractId": "siva8978", "html": "<p>PREFERENCE SHAREHOLDER AGREEMENTTHIS AGREEMENT is made on the&nbsp;$$Contract Start Date$$ BETWEEN&nbsp;CRADLE WEALTH ...

Can someone help me troubleshoot the issue I'm having with this jQuery API function?

Greetings everyone, I'm facing an issue with my jQuery code. I am attempting to use the CoinMarketCap API from cryptokickoff to showcase cryptocurrency statistics on my website. I understand how to display them, but the appending process to my column ...

Create a fully responsive introduction page with three columns using Bootstrap, ensuring that the height of the

Currently, I am in the process of designing a website for a restaurant, hotel, and vineyard. My goal is to create three separate websites that are linked through one introductory page. The concept for the intro page involves three columns displayed side b ...

Using JQuery to make POST requests is successful, however, utilizing the XMLHttpRequest object to make

Currently, I am attempting to make a POST request from Javascript to my server in PHP but without utilizing jQuery. The following code successfully sends the required data to the database: var msg = {}; msg['name'] = 'joe'; msg['m ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

Obtain element values using Protractor and WebDriverJS and store them in an array of objects

Coming from a Java+WebDriver background, I am new to Protractor, WebdriverJS, and Jasmine. In the image displayed, my goal is to hover over all bubbles and retrieve the tool tip values (city, sold, connected), assign them as objects to an array, and return ...

Tips for ensuring your background image is fully displayed and covers the entire size

My dilemma lies within the header div. My intention is to have it fully covered with a background image without any cropping. However, the current setup seems to be stretching and cutting off parts of the image. Here is my CSS code: .header { bor ...

Load Vue dynamically to implement reCAPTCHA script

I am looking for a way to dynamically load a script like recaptcha specifically within the Register.Vue / login.Vue component. <script src="https://www.google.com/recaptcha/api.js?onload=vueRecaptchaApiLoaded&render=explicit" async defer> </s ...

Employ various iterations of the leaflet library

Creating a web application using React and various libraries, I encountered an issue with conflicting versions of the Leaflet library. Currently, I am incorporating the Windy API for weather forecast, which utilizes Leaflet library version 1.4.0. However ...

Creating a container that matches the dimensions of its neighboring container without using relative or absolute positioning

I am seeking a solution to make the ".on-the-left" container have the same size as the ".on-the-right" container, but without relying on relative or absolute positioning. Here is the visual outcome I am aiming for: https://jsfiddle.net/NicoZZZ/osbL16z9/28 ...

Creating JSON objects for ASP.net MVC 4 AJAX calls: A Guide

Upon discovering vsdocs files, I envisioned a way to incorporate intellisense into my JQuery files for handling objects sent to my ASP.net MVC backend. It's like having an MVC Model specifically for jQuery Ajax callbacks. You can find the following ...

What steps can I take to address this Material UI alert and deliver a solution that adds value?

I am currently working on fetching API data (specifically category names) from the back-end (Node.js) to the front-end (React). My main objective right now is to populate a Select component from Material UI. To fetch the API data, I am utilizing Express an ...

Use jQuery to place the initial 3 elements within a div

Currently, I am dynamically pulling content into li elements using ASP.NET. My goal is to wrap a specific div class around the first 3 li items in the list only. Here is an example: <ul class="wrapper"> <div cl ...

Error: The function jquery_1.default is not recognized by webpack

I am encountering an issue with using external imports of jQuery in webpack. Despite trying different import syntaxes such as import $ from 'jquery', import * as $ from 'jquery, and const $ = require('jquery'), I continue to receiv ...

Using JavaScript, retrieve the ID of a child element by utilizing details about the parent element

I have implemented a JavaScript function that creates a div element. Within this div, there are multiple checkboxes as child elements. My goal is to use a loop to extract the ids of all these checkboxes. The div has been assigned to a variable named: o ...

Navigating through Router Parameters in VueJS

Currently, I am in the process of developing a blog using Vue.js and I am still learning the ropes. To explain briefly, I have a list of dynamic elements that are displayed on the screen. When a user clicks on one of these items, I want to navigate to the ...

Preserve the datepicker even after selecting a date

I am currently using the datepicker feature from jQuery UI in my project. Below is a snippet of my initial code: $('#fromDate').datepicker({ showOtherMonths: true, minDate: 0, dateFormat: 'dd MM yy', onSelect: function(dateTex ...

Achieving the resolution of a Promise amidst the failure of a separate promise

I need to handle a situation where a promise is resolved regardless of the success or failure of an ajax call. I attempted to use the following code snippet: new Promise(function(resolve, reject) { $.ajax({ url: "nonExistentURL", headers: { ...

Material UI Grid List rows are displaying with an unusually large gap between them, creating a

Currently, I am utilizing Material UI in combination with Reactjs. One particular issue that I am encountering involves the Grid List Component. In my attempt to establish a grid of 1000x1000px, I have specified the height and width within the custom gridL ...

Exploring JavaScript: Accessing an array object within another object

I'm having trouble accessing an array object within an object in JavaScript. The object structure is as follows: categories: Array(5) 0: name: "Electronics" subCategories: Array(16) 0: name: "Video Games & Accessories" __typena ...