Learn the position of a div element that appears following the lazy loading of images

I am struggling to make a div sticky below a set of lazy load images. The issue lies in the fact that the offset of the div keeps changing due to the lazy loading images pushing it down. There are 4 images with unknown heights, making it difficult to accurately determine the offset needed for the sticky behavior. I attempted to use the appear event on the last loaded element but did not achieve the desired results. Any guidance on how to solve this problem would be greatly appreciated. My goal is to obtain the offset of the sticky div in order to implement a check on the scroll event.

<div id="someWrapper">
    <img class="lazy" data-original="someImageURL"></img>
    <img class="lazy" data-original="someImageURL"></img>
   <img class="lazy" data-original="someImageURL"></img>
   <img class="lazy" data-original="someImageURL"></img>
   <div class="sticky">SomeContents</div> <!-- want to make this sticky on scrool -->
</div>

Answer №1

After experimenting and conducting research, I was able to achieve the desired outcome using the following code:

function activateStickyScrollEvent(offSetValue){
//code to trigger scroll event

}

var lazyLength=$('#someWrapper lazy').length;
var lazyCount=0;
$('#someWrapper lazy').one('appear',function(){
      ++lazyCount;
      if(lazyCount===lazyLength){
         var getWrapperOffset=$('#someWrapper').offSet().top;
         activateStickyScrollEvent(getWrapperOffset);

})

Answer №2

It's important to verify if the last image in the set has been loaded and then check for the element's offset. Here is a demonstration of how this can be accomplished. Feel free to customize the code to fit your requirements.

//Reference to the wrapper
var $wrapper = $("#someWrapper");
//Reference to the last image in the set
var lastImgSrc = $wrapper.find(" > img:last").attr("data-original");

var image = new Image();
image.onload = function () {
    //Perform actions on load...
    var offset = $wrapper.find(".sticky").offset();
    alert (offset.top);
}
image.onerror = function () {
   //Perform actions on error...
}
image.src = lastImgSrc;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someWrapper">
    <img class="lazy" data-original="someImageURL" />
    <img class="lazy" data-original="someImageURL" />
    <img class="lazy" data-original="http://dreamatico.com/data_images/sea/sea-4.jpg" src="http://dreamatico.com/data_images/sea/sea-4.jpg" width="100%" />
    <img class="lazy" data-original="http://dreamatico.com/data_images/sea/sea-3.jpg" src="http://dreamatico.com/data_images/sea/sea-3.jpg" width="100%" />
    <div class="sticky">SomeContents</div> <!-- make this sticky on scroll -->
</div>

I trust this information will prove beneficial.

Answer №3

To track the loading of images and determine the offset (OFFSET in this case) :

$(function() {

    function imageLoadingStatus() {
       count--; 
       if( count === 0 ) {
           // At this point, all your "lazy" images have been loaded
           var OFFSET = $('#someWrapper').offset().top;  <---- retrieve the offset value 
       }
    }

    var imageList = $('.lazy'),
        count = imageList.length;  // initializing the counter

    imageList.each(function() {
        if( this.complete ) {
            imageLoadingStatus.call( this );
        } else {
            $(this).one('load', imageLoadingStatus);
        }
    });
});

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 steps to view the JavaScript file of a website using a web browser's inspector tool

As I was exploring the web browser inspector tool, I attempted to view the JavaScript source code of a website (). However, all I could find was HTML code (view-source:). I am eager to access the JS file from my browser directly. How can I achieve this? I ...

Creating a banner using four grid elements, with each element containing four child elements, is a simple process that can

Can you assist me in recreating my idea from an image? I am having trouble understanding how to select and place other elements, and then return them to their original positions after deselecting... I attempted to use a grid but it did not work properly. ...

Locate a particular text element following a specific anchor tag using jQuery

Consider the scenario: <a href="foo">Subject</a> &gt; <a href=bar">Negotiation</a>, 1) Can you target the "&gt"; that comes after this specific a tag using jquery? I only want to select certain occurrences, not all on the ...

Fetch external navigation and refresh hyperlinks

After spending an hour searching on Google without finding a solution to my problem, I decided to reach out here for help. Currently, I have a site hosted on a CMS platform and recently created a WordPress blog on a subdomain on a new server. Unfortunatel ...

Is there a way to eliminate the filter icon from the material-table component?

I'm looking to customize my table by removing the filter icons and having blank input boxes instead. I've tried using the column prop filterCellStyle, but the icon can't be accessed since it's inline styling. import React, { Children ...

How to find a collision between a spherical object and a triangular shape in a three

In my research, I am exploring the possibility of detecting collisions between a triangle and a sphere in three.js. Currently, I have devised a method using the raycaster and the sphere's vertices. However, this approach has proven to be unreliable a ...

What causes the Invalid Form Body error to appear when using the Discord API?

While developing a Discord bot, I encountered an issue with creating a ping command. The error message received was as follows: (node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body embed.footer.icon_url: Scheme "flashybot& ...

Less-middleware in Node.js not automatically compiling files

I've incorporated the less-middleware into my Node.js Express app, but I'm encountering an issue. Whenever I update my screen.less file, it doesn't recompile automatically. To trigger a recompilation, I have to delete the generated .css file ...

What causes the discrepancy in the output values of the sha1 algorithm when using the packages object-hash and crypto/hashlib

On my frontend, I have implemented a JavaScript function that compares two sha1 hashes generated by the object-hash library. This is used to determine if there are any changes in the input data, triggering a rerun of a processing pipeline. To interact wit ...

What is the best way to incorporate plugins designed for various jQuery versions onto a single webpage?

I have integrated three jQuery scripts into an HTML page, including a Colorbox plugin for the gallery, a popup plugin for a reservation form, and a sliding jQuery script for the footer. However, I am facing issues where either the close button on the pop ...

A modern CSS solution for a fixed columns and header layout in a scrollable table

How can I create a table with minimal JavaScript using modern CSS? I am aiming to include the following features: Fixed column(s) (positioning and width) Scrollable in both X and Y axes Responsive in the X axis (for non-fixed width columns). https://i. ...

When I remove a user as admin, I am unable to retrieve all users to update the data table

I am currently working on an Admin Dashboard that includes a section for users. This section features a simple table displaying all the users in the MongoDB database along with some information. Additionally, there are functionalities to add a new user and ...

What you see is what you get when it comes to effortlessly copying and pasting

As a web developer, I am aware that images cannot simply be copied from a local machine and pasted into a website - they must be uploaded. I have experience with wysiwyg tools like TinyMCE and FCKEditor, but my client is frustrated about not being able to ...

Combine two objects and discard any duplicate keys

I have two objects named original and custom. My goal is to merge the content from custom into original, but only update the keys in original that are also present in the custom object. Here is an example scenario: var original = { coupon: { ...

The function toggleClass() is malfunctioning

The .toggleClass() method seems to only be adding the "class" attribute to my selection, resulting in: <div id="toggle" class> ... rather than: <div id="toggle" class="on"> ... I've been trying to solve this issue for about 2 hours now ...

The animation for the CSS background image simply refuses to cooperate

My goal is to create a CSS background animation using the Body tag. Below is the code I am currently using: body { animation-name:mymove; animation-duration:5s; animation-direction:alternate; animation-iteration-count:infinite; -webkit-animation-name:mymo ...

Angular 2 ngSubmit triggers unexpectedly on occasions when it is not supposed to

Currently, I am working on developing an Ionic 3 application with Angular 2 and TypeScript. In the app, there is a form that is responsible for sending data to our server. The issue I am facing is that whenever I click on the following button: <butto ...

Mixing controllers with the same name in AngularJS from different modules can lead to

Recently, while working on an AngularJS web application with multiple sub-modules, I encountered a situation where two sub-modules had controllers with the same name due to them both having CRUD functionality. Here's a snippet of the code structure: ...

The $ symbol is not recognized in this context [jQuery, MasterPage, UserControl, Shared/static Event handler, external javascript]

Unfortunately, I am facing a challenge in replicating this issue outside of my application. If anyone is willing to assist, I have a VS2012 project that can be shared for further investigation. The functionality works fine in isolation but fails in a large ...

What are the different approaches for creating a website that adapts to different screen sizes and devices

The popularity of responsive web design is growing rapidly. While many recognize Twitter Bootstrap as a top framework, there are other options worth exploring. Several impressive examples of responsive websites, such as Smashing Magazine and CSS Tricks, ...