Several adhesive panels on a dynamic webpage

In the content area of my page, a dynamic number of rows are generated. Each row consists of two columns: a side block and a content area. The goal is to have the side block stick while the page scrolls down until the next block appears and pushes the previous one away, becoming sticky itself. Below is the HTML structure:

<div class="container">
    <div class="row">
        <div class="col-md-4 sticky">
            <h2>Example</h2>
            <p class="page-side-block">...</p>
            <a href="#" class="action-button">...</a>
        </div>
        <div class="col-md-8 col-md-offset-4">
            <p>...</p>
        </div>
    </div>
    ...

I've managed to make the first block sticky, but I'm unsure how to achieve the desired functionality for subsequent blocks. Any assistance would be appreciated.

Below is the JavaScript code (using mootools) that I am currently using. Please note that it may not work with the provided HTML markup, as I have made adjustments for clarity:

window.onscroll = function() {
    var stickyBlock = $('sticky-block');
    if (window.getScroll().y > 235) {
        stickyBlock.setStyles({
            position: 'fixed',
            top: '100px',
            width: "350px"
        });
    } else if (window.getScroll().y < 235) {
       stickyBlock.setStyles({
            position: 'absolute',
            top: 0,
            width: null
       });
    }
}

It's worth noting that the new w3c specs have introduced a position: sticky; property, which could eliminate the need for JavaScript in this scenario. Unfortunately, browser support for this feature is currently limited, as indicated here.

If anyone has insight on resolving this issue, I would greatly appreciate your input. Thank you!

Answer №1

It's a bit late at night here, but I wanted to share a suggestion with you.

If you track all positions and listen for scroll events, you can compare the initial positions with the scroll position and fix elements as needed.

In my example, I utilize the .pin() method from MooTools More, so as not to reinvent the wheel.

Example: http://jsfiddle.net/2AZ28/

Here is some MooTools code:

var stickyBlock = $$('.sticky').map(function(el){
    return {
        elem: el,
        initialPos: el.getPosition().y,
        height: el.getHeight()
    };
});
window.addEvent('scroll', function(){
    var currentScrollPos = window.getScroll().y;
    stickyBlock.each(function (el, index) {
        if (el.initialPos <= currentScrollPos){
            el.elem.pin();
            if (stickyBlock[index + 1] && (stickyBlock[index + 1].initialPos - el.height <= currentScrollPos)) el.elem.setStyle('top', stickyBlock[index + 1].initialPos - el.height - currentScrollPos);
        } else {
            el.elem.unpin();
        }
    });
})

There might be room for further optimization, but I hope this aids in addressing your query.

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

Can I use my local network/browser to download an html file from a webpage as if I manually downloaded it using javascript or nodejs?

As someone who is relatively new to javascript/nodejs and its packages, I have a question about downloading files. Is it feasible for me to download a file using my own local browser or network? Typically, when researching how to scrape or download html ...

Ways to connect css file to ejs views in nodejs

Currently, I am tackling a beginner node.js server project. While I have successfully managed to render dynamic HTML using ejs templates, I seem to be facing difficulties when it comes to linking CSS styling to these templates. In an effort to address thi ...

What steps can be taken to confirm the accuracy of input before sending it

Having trouble with validating input before submitting? Every time I run submit(), something seems to be going wrong :( const [value, setValue] = React.useState(""); const [error, setError] = React.useState(""); const validate = () => { value.length ...

The use of an Authorization header is not compatible with HTTP GET requests

I recently incorporated VueSession into my project to handle user sessions. One of the components in my application is a login form that communicates with my backend (Django) to obtain a JWT token. However, I encountered an issue where although the login p ...

Is it possible to visually distinguish the selected mat-grid-tile? Particularly when they are being created dynamically

On the user interface, I have a dynamic display of mat-grid-tile within a mat-grid-list. These tiles change in number and data based on backend values. When a user clicks on a mat-grid-tile, it triggers a function that receives the tile's data. My goa ...

Storing information in Firebase using React.js

When storing an object in Firebase, I expected the structure to be as shown in the image below. However, what I received was a generated running number as a key. This is the code I used to store the object in Firebase: var location = []; location.push({ ...

Create a Boostrap navbar with a form and links aligned to the right using the navbar

I'm trying to use navbar-right on a navbar-form and a navbar-nav, but the form ends up on one row and the nav links on another row on the right. How can I make the navbar display the brand on the left and have a search field followed by nav links on t ...

What is the best way to create a self-referencing <div> in HTML?

After extensive research, I turn to seeking advice and guidance on Stack Exchange. I have a seemingly straightforward goal in mind. I want to create a <div> id/class that will automatically generate a link to itself using scripting of some sort. Be ...

Struggling with Angular 8: Attempting to utilize form data for string formatting in a service, but encountering persistent page reloading and failure to reassign variables from form values

My goal is to extract the zip code from a form, create a URL based on that zip code, make an API call using that URL, and then display the JSON data on the screen. I have successfully generated the URL and retrieved the necessary data. However, I am strug ...

Ways to heighten the `RadComboBox` `DropDownHeight` featuring `Templates`

One of the challenges I'm facing involves a RadComboBox setup like this: <telerik:RadComboBox ID="RadComboBoxNames" runat="server" Width="470px" DropDownAutoWidth="Enabled" MaxHeight="363px" Skin="MySkin" EmptyMessage="Select" High ...

Error: The property 'language' is undefined and cannot be read

Struggling to execute the App-test.js file provided by React Native in the __test__ directory: import 'react-native'; import React from 'react'; import App from '../src/app'; // Note: test renderer must be required after rea ...

What could be the reason for the navigation bar menu items not showing up in the sample application of the twitter.bootstrap.mvc4 package?

After setting up a new MVC4 web application project in VS2012, I decided to add the http://www.nuget.org/packages/twitter.bootstrap.mvc4.sample/ nuget package. However, upon running the sample application, I encountered an issue where the navigation menu i ...

Retrieving a specific variable from a cookie value that is stored within a JSON array

Is there a way to pass a single variable from a JSON array stored in the qookie file value to JavaScript? The qookie code looks like this: <?php $cookie_key = 'count'; CookieManager::store($cookie_key, json_encode(array( 'SameSite&ap ...

The clash between Angular's ng-if directive and Bootstrap's popover feature causing unexpected

<div class="form-group" ng-if="firstname"> <label>First Name</label> <input readonly type="text" class="form-control" id="first_name" ng-model="firstname" placeholder="First Name"> <a href="" data-toggle="popover" dat ...

Express.js - Monitoring for server closure

I have a Node.js application that utilizes Express. Within this application, there is a section of code structured as follows: const app = require('./app'); const port = process.env.PORT || 8080; const server = app.listen(port); server.on(&apos ...

combine blank cells in table generated with vuejs

I am attempting to display a table of students where each column represents a subject, and underneath each column are the names of the students who failed in that particular subject. The challenge I am facing is that my data is structured in rows instead o ...

After updating the state, the Next.js axios call experiences a delay before executing the desired action

I am currently working on a NextJS project that relies on Axios for handling API calls. Within this project, there is a loading state implemented to show a loading spinner when making these API calls. However, I have encountered an issue where after click ...

Constructing a horizontal slider using vertically floating divs

Struggling to create a basic horizontal image slider using overflow:hidden and floating divs. Despite efforts, the divs keep stacking vertically instead of horizontally. Numerous online examples have been attempted without success. HTML: <div id="slid ...

Employing a function to concatenate promises

In my coding process, I have come across a situation where I need to fetch content and then save it using two separate functions. Each function performs a different task based on the type of content provided. These functions act as helper functions in my o ...

Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links: <p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br> 4 Bedrooms x 2.5 Bathrooms</p> <p><a href="#" class="floorplan" data-id="wood">< ...