Angularjs directive experiencing intermittent firing of IntersectionObserver

Currently, I am in the process of integrating lazy loading using the IntersectionObserver within my angularjs application.

However, there seems to be an issue where the callback function of the observer is not always being triggered when scrolling up and down.

The directive implemented looks like this:

var app = angular.module("test", []);

app.directive("inViewport", function() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {    
      const observer = new IntersectionObserver(callback);
      const img = angular.element(element)[0];
      observer.observe(img);

      function callback(changes) {
        changes.forEach(change => {
          change.target.classList.toggle(
            "visible",
            change.intersectionRatio > 0
          );
        });
      }
    }
  };
});

For a demonstration, you can check out this pen.

Answer №1

Make sure to use change.isIntersecting instead of change.intersectionRatio > 0 when using change.target.classList.toggle.

Since IntersectionObserver operates asynchronously, there may be a slight delay when the callback function is called.

var app = angular.module("test", []);

app.directive("inViewport", function() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {
      
      const observer = new IntersectionObserver(callback);
      
      const img = angular.element(element)[0];
      observer.observe(img);

      function callback(changes) {
        changes.forEach(change => {
          change.target.classList.toggle(
            "visible",
            change.isIntersecting
          );
        });
      }
    }
  };
});
.main div {
  background: green;
  height: 100px;
  width: 100%;
  margin: 10px;
}
    
.main div.visible {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.17/angular.min.js"></script>


<div ng-app="test" class="main">
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
</div>

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

I require limitless onclick functionality, but unfortunately, transitions are not functioning as expected

I'm currently working on creating a dynamic photo gallery, but I've encountered a couple of issues that need to be addressed... The "onclick" function in my JavaScript only allows for a single click, whereas I need it to be able to handle mul ...

Is there a way to adjust the width of a table cell in Material UI using React?

I encountered a problem where I am attempting to adjust the width of a table cell, specifically in Typescript. However, I am only able to choose between medium and small sizes for TableCellProps. Is there a workaround for this issue? I am looking to expand ...

How do I show a variable within my react-native render function?

I attempted to showcase information fetched by a function in my React Native rendering application. Even though I successfully retrieved the data, I am encountering issues when trying to display it on the app. This is the snippet of my code: import Reac ...

`Developing reusable TypeScript code for both Node.js and Vue.js`

I'm struggling to figure out the solution for my current setup. Here are the details: Node.js 16.1.x Vue.js 3.x TypeScript 4.2.4 This is how my directory structure looks: Root (Node.js server) shared MySharedFile.ts ui (Vue.js code) MySharedFi ...

What is the process of sending an IPC message from a renderer to a webview within the same renderer

Is it possible to use Electron's ipcRenderer to send a message to a <webview> element? I attempted the following: var webview = document.getElementsByTagName("webview")[0]; webview.send("test", "testing"); as well as ipcRenderer.send("test" ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

Developing a Monitoring-Frontend Application with backbone.js

I am in the process of developing a tool for monitoring and analyzing statistics. The current setup is as follows: Collector-Backend: This component receives queries in JSON format from the frontend, fetches and stores them in a cache, and then notifies ...

Issue: The DLL initialization routine failed for electron, but it works perfectly fine on node.js

Currently, I am facing an issue while attempting to load a custom module in electron that is written in D using the node_dlang package. The module loads successfully with node, but encounters failures within electron. The test run with node, which works w ...

What is the best way to trigger actions from child components within React Redux?

My server contains the following code snippet: <ReactRedux.Provider store={store}><Layout defaultStore={JSON.stringify(store.getState())}/></ReactRedux.Provider> The <Layout> component includes more nested components. Further dow ...

I'm having trouble setting up Stripe Elements in PHP. It seems like there's a communication issue between my PHP code and my JS

New to setting up Stripe Elements, I've followed the documentation closely. Installed the necessary JS modules, included the Stripe API, and connected it to the Stripe JS. In my index.php file, PHP script is at the top with HTML and JavaScript below i ...

Having trouble aligning a div in the middle of a slick-slider item using flex styling

I've created a slick slider component in Vue, and I'm facing an issue with centering a circular div inside each of the slider items. Despite trying to align and justify center along with adding margin:auto for horizontal centering, I can't s ...

Error Encountered During Serialization with ASP.Net AJAX and JavaScript

Encountered an error message stating "Out of Stack Space" while attempting to serialize an ASP.Net AJAX Array object. Below is a breakdown of the issue with simplified code: Default.aspx MainScript.js function getObject(){ return new Array(); } ...

Flow - secure actions to ensure type safety

Currently implementing flow and looking to enhance the type safety of my reducers. I stumbled upon a helpful comment proposing a solution that seems compatible with my existing codebase: https://github.com/reduxjs/redux/issues/992#issuecomment-191152574 I ...

What is causing the malfunction in this straightforward attrTween demonstration?

Seeking to grasp the concept of attrTween, I am exploring how to make a square move using this method instead of the simpler attr approach. Despite no errors being displayed in the console, the following example does not produce any visible results, leavin ...

Find the most accurate color name corresponding to a hexadecimal color code

When given a hex-value, I aim to find the closest matching color name. For instance, if the hex-color is #f00, the corresponding color name is red. '#ff0000' => 'red' '#000000' => 'black' '#ffff00' = ...

What is the best approach: Referencing schema within properties or including it as an array in Mongoose?

Consider the scenario where we have two schemas, User and Post. Should we include a reference to User in Post's properties or should we add an array of Post schema inside User schema? Which approach is more efficient in terms of performance and other ...

What is preventing me from using Selenium/Javascript to control Firefox on Ubuntu 22.04, when I am able to do so with Python?

My python script effectively controls Firefox using Selenium: from selenium import webdriver from selenium.webdriver.common.by import By driver = webdriver.Firefox() driver.get("https://dev.to") driver.find_element(By.CLASS_NAME, "crayons ...

What causes variables and functions to behave differently when it comes to hoisting?

I've recently been delving into some documentation and have noticed some inconsistencies in hoisting patterns within JavaScript. Consider the following examples: When it comes to functions, function abc(){ console.log("worked") } abc(); OUTPUT : ...

In AngularJs, I am unable to prevent my ui-sref anchor tag from being triggered using event.preventDefault()

Here is the code snippet I am working with: <a ui-sref="MyModule">My Module</a> When the link is clicked, the following function will be triggered: $scope.$on("$locationChangeStart", function (event) { if (!confirm('You have un ...