Intersection observer automatically removes images from carousel (Siema) after they have been viewed

Check out this example to see the issue I'm facing.

I've implemented an intersection observer for lazy loading images, here's the code:

const pictures = document.querySelectorAll("[data-src]");

function loadPicture(pic){
    const src = pic.getAttribute("data-src");
    if (!src) { return; }
    pic.src= src;
}

const picOptions = {
    threshold: 0,
    rootMargin: "0px 0px 300px 0px"
};

const picObserver = new IntersectionObserver( (entries, picObserver) => {
    entries.forEach(entry => {
        if(!entry.isIntersecting){
            return;
        } else {
            loadPicture(entry.target);
            picObserver.unobserve(entry.target);
        }
    })
}, picOptions);

pictures.forEach( picture => {
    picObserver.observe(picture);
});

The issue occurs when I cycle through the Siema carousel - the first and last images seem to "unload", reverting back from `src` to `data-src`, even though they were supposed to be ignored after being observed.

If you click 'prev' in the example, you'll notice the first image disappearing, although it was already loaded.

Why is this happening and how can I fix it?

Update: Fixed fiddle now available at this link, all thanks to @ohladkov

Answer №1

The reason behind this issue is related to the value of loop: 1. The page only contains 6 pictures when it is loaded using

const images = document.querySelectorAll("[data-src]")
, but the slider initialization requires 10 images. To resolve this, you should fetch the images and trigger your observer during the slider initialization. Siema provides an onInit callback that can be utilized for this purpose. Here's a sample implementation:

onInit() {
  const el = document.querySelector(this.config.selector); // fetch siema container
  const images = el.querySelectorAll("[data-src]"); // extract all siema images

  images.forEach( image => {
    imgObserver.observe(image);
  });
},

I trust this solution will prove helpful to you!

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

Navigating a table while keeping headers in place at the top

Trying to construct a table where the thead remains fixed while the tbody scrolls. Utilizing percentages and fixed width for cell size determination, aiming for uniformity and alignment between percentage td's and thead headers. Referenced JSFiddle d ...

JavaScript: Populating an Array with Image URLs Using a Loop

My image gallery project has hit a roadblock and my JavaScript skills are not up to par. Maybe it's time to brush up on the basics with a good book from the library. Here's what I want to achieve: 1. Create an array of URL's for each imag ...

I need assistance in locating an error; the error message states that $ is not defined and an object is expected

Issue with $ not being defined, object expected.. I am trying to verify if all sets of radio buttons are checked when a button is clicked! Please help. <script type="text/javascript> $(document).on('click', 'form', function () { ...

Modify a property within an object stored in an array using React with Redux

When trying to dispatch an action that updates values in the redux state by passing an array, I encountered an issue. It seems that despite attempting to update the array by changing object values, I kept facing this error - "Cannot assign to read only pro ...

Stripping quotation marks from CSV information using Javascript

After performing a fetch request using JavaScript, I have converted JSON data into CSV format. datetime","open","high","low","close","volume" "2020-01-28","312.48999","318.39999","312.19000","317.69000","31027981" "2020-01-27","309.89999","311.76001","30 ...

Guide on utilizing multiple ng-apps alongside multiple controllers

Having trouble accessing controller values in different ng-apps? Here's a setup with two ng-apps and their controllers, where you may encounter errors when trying to access the value of one controller in another. Need some assistance with this issue. ...

`Why won't Puppeteer let me pass a variable into a page URL parameter?`

Encountered an error message: Error: Protocol error (Page.navigate): Invalid parameters Failed to deserialize params.url - BINDINGS: mandatory field missing at position 49... The issue arises when trying to pass a variable into the page URL parameter as s ...

Is there a way to make a try-catch block pause and wait for a response before moving

I've been successfully retrieving data from my Firestore database, but I've encountered a major issue that I can't seem to resolve... Whenever I click the "Read Data" button, I have to press it twice in order to see the console log of the d ...

Displaying JavaScript - Nothing to Echo in PHP

Using PHP to echo a JavaScript block, I have encountered an error message. echo "<script language='javascript' type='text/javascript'> jQuery(document).ready(function($){ var $lg = $('#mydiv'); ...

Looking for the properties of the ServerResponse object in node.js - where can I locate them?

Currently, I've been diving into the book Node.js In Action. Chapter 9 introduces a message module with a function that has left me puzzled about the 'this' object when calling res.message. To gain clarity, I decided to print out the name of ...

Modify the directive when the scope variable undergoes changes

Utilizing an http request, I am retrieving data from a json file that I then utilize in my controller. app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) { //Getting data from the s ...

Navigation Bar Dropdown Menu Not Responding to Clicks

I'm having trouble implementing a dropdown menu in my navigation bar that should appear when the user clicks and disappear when they click anywhere outside of it, similar to Facebook's dropdown menu with options like logout. However, for some rea ...

Divergence between two distinctive occurrences in Google Analytics

Why are there differences in the number of unique events recorded by Google Analytics for two consecutive events? I have set up onClick tracking for a button. When the button is clicked, an event (Event 1) is sent to Google Analytics and a CSS-selector ap ...

Is it possible to incorporate npm modules into a browser and utilize them locally on a personal computer?

This is my first time working with npm modules and node.js, so I find it quite challenging. I have a JavaScript code with multiple data points and I need to find the closest city to each of them. In response to another question on Stack Overflow (Reverse ...

"Unlock the power of Meteor: dynamically serve up the specific range of items

I am facing a challenge with my vast collection of over 5000+ records. I aim to display the records in groups of 10 for easier viewing. How can I update the data dynamically to achieve this? Here is what I have attempted so far: In my server.js file : M ...

The process of using Jest to test whether a React component correctly renders a list

I've been diving into the world of unit testing and recently developed a small React application that showcases a list of Pokemon. My goal is to create a unit test that verifies if the list renders correctly. However, when I generate a snapshot, it on ...

AngularJS - Introducing blurred delay

Here is the code snippet I am working with: <div class="staff"> <input ng-model="user" ng-focus="isFocused = true;" ng-blur="isFocused = false;/> <div class="matches" ng-if="isFocused"> <div ...

Issue encountered while utilizing JQueryUI alongside TypeScript and the definition file from DefinitelyTyped

Currently, I'm attempting to incorporate JQueryUI with TypeScript by first installing JQueryUI using npm install jquery-ui-dist, and then installing JQuery with npm install jquery. Additionally, I have included the definition files from DefinitelyType ...

Explaining Vue.js actions and mutations in detail

Can someone help clarify the relationship between these functions for me? I'm currently learning about Vue.js and came across an action that commits a mutation. The Action: updateUser({commit}, user) { commit('setUser', {userId: user[&ap ...

What is the best way to dismiss the modal window in React upon clicking the "Add product" button?

Hello all, I'm having trouble figuring out how to close the modal window in React. I want it so that when the user clicks on the "Add" button, a modal window opens for data input, and then upon clicking the "Add product" button, the window closes imme ...