Loading images lazily using knockout.js

I have been working on implementing lazy loading for images using knockoutjs binding. I previously successfully implemented lazy loading without the knockoutjs framework, but I am unsure of how to achieve this with knockoutjs binding. Below is my HTML code:

     <div class='liveExample'> 
        <div class="row">
           <div data-bind="foreach: items">
              <div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
                 <img data-bind=" attr: { src: $data }" class="lazy" />
              </div>
           </div>
       </div>
    </div>

Javascript:

var SimpleListModel = function(items) {
    this.items = ko.observableArray(items);
    bind(this);  // Ensure that "this" is always this view model
};

var pictures = []; //Initialise an empty array

for (var i = 0; i = 10 ; i++) {
    var image; //This is a placeholder
    image = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the src attribute     (imageFiles[i] is the current filename in the loop)
    pictures.push(image); //Append the new image into the pictures array
}

ko.applyBindings(new SimpleListModel(pictures));

Check out the implementation on jsfiddle

Answer №1

I was able to successfully implement this solution by inserting an additional div tag before the foreach binding and then assigning the afterrender event to the parent div.

   <div class="row">
      <div data-bind='template: {afterRender: myPostProcessingLogic }'> 
<div data-bind="foreach: {data: items} ">
    <div class="col-lg-4 col-md-4 col-sm-4 " style="padding: 0px">
       <img data-bind=" attr: { 'data-original': $data }" class="lazy" style="min-width:100px; min-height:50px;"  />
    </div>
</div>
   </div>

</div>

Javascript

var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
   this.myPostProcessingLogic = function(elements) {
        $("img.lazy").lazyload({
         effect: "fadeIn",
         effectspeed: 2000
       });
   }
};

var pictures = []; //Initialize an empty array
for (var i = 1; i < 100 ; i++) {
    var imageUrl = 'http://dummyimage.com/300x200/000/fff&text=' + i; //Set the image url
    pictures.push(imageUrl); //Add the new image to the pictures array
}
ko.applyBindings(new SimpleListModel(pictures));

Here is the jsfiddle

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

How can an Express.js server detect when a browser has been closed or reloaded?

Currently tackling a project with an Express.js server. One query I have is how can this server detect when one of its users (browser) has been closed or reloaded? Any insights on this would be greatly appreciated! ...

The perplexing simplicity of closure

Currently, I am endeavoring to enhance my knowledge of JavaScript closures. Let's consider the following two scenarios in Node.js: function A(){ console.log(data); //this will result in a null pointer } module.exports = function(data){ re ...

An error occurred while trying to upload the image: Undefined property 'subscribe' cannot be read

Recently, I implemented a create post function that allows users to fill in the title, content, and upload an image. However, I encountered an issue where the progress bar fills up and the image gets uploaded to Firebase successfully, but it doesn't a ...

Creating an interactive map on an image using HTML and drawing circles

I've been experimenting with drawing circles on images using the map property in HTML. I have an image set up, and when clicking on the image in JavaScript, I'm adding the area coordinates for the map property. However, I keep encountering a null ...

Modify the color of the header on Material-UI Date Picker

I recently integrated a Material-UI Date Picker into my React Single Page Application and now I'm facing an issue with changing the header color. I attempted to modify it using the muiTheme palette property, but unfortunately, the header color remains ...

Toggle the visibility of the search Div using Angular UI

When using angular UI buttons, users can select search criteria by choosing between Patient, ID, or Date. If Patient or ID is selected, the searchByText div will be shown. If Date is selected, the searchByText will be hidden and the SearchBydateRange wil ...

Is there a way to integrate PHP functionality into JavaScript?

When it comes to using JavaScript and PHP together, a common challenge is retrieving information from a database and utilizing that data in a JavaScript function. In my case, I need this functionality for implementing password change functionality on a w ...

Guide to exporting specific files in Node.js or Deno

Utilizing the export keyword in JavaScript allows us to export any content from one file to another. Is there a way to restrict exports to specific files, preventing other files from importing them? export const t = { a: 'this will only be exported fo ...

The step-by-step guide to implementing async/await specifically for a 'for loop'

Is there a way to make 'submitToTheOthers' function run after 'let items = []' has completed, without needing an await within 'submitToTheOthers'? I am considering using await within the for loop in 'submitToTheOthers&apo ...

Unlimited Caching: A Guide to Storing HTTP Responses permanently

Is there a way to send an HTTP response that will be cached by any client indefinitely, so that the browser can retrieve it from the local file system without making any new HTTP requests when needed? Just imagine using this for versioned client code in a ...

Executing a JavaScript function when an element is clicked using inline

Is it possible to write the code below in a single line? <a href="#" onClick="function(){ //do something; return false;};return false;"></a> As an alternative to: <a href="#" onClick="doSomething(); return false;"></a> functio ...

Showing a notification on the screen upon redirection to the index page

On my main index page, there are 18 divs representing different books. When a user clicks on a div, they can see details about the book such as title, author, and summary. There's also an option to add the book to a Collections array by clicking the " ...

Challenges of aligning a modal overlay in the middle of mobile screens

Currently, I am developing a website and encountering a specific issue with the modal structure. When viewing it on Codepen using Chrome devtools and toggling the device toolbar to simulate mobile screens, everything appears fine. However, when opening the ...

Translate a portion of a painting by utilizing context.putImageData()

I am attempting to gradually fill a canvas with pieces of the original image. To achieve this, I need each square of the image to be filled in iteratively on the canvas. To optimize performance, my approach involves rendering the original image onto an of ...

What could be the reason for the GET method being executed after the DELETE method in ExpressJS?

Whenever I trigger the DELETE method in my Express app, it seems that the GET method is automatically invoked right after. This results in an error within my Angular code stating that it expects an object but receives an array instead. Why is the GET meth ...

Standing alone, an argument can never be fully validated without

Recently, while delving into the valuable resource titled Effective TypeScript by Dan Vanderkam, I stumbled across an intriguing scenario that left me puzzled. Within a code snippet presented in the book, there was a line - shape; that seemed perplexing ...

Securely getting a data point from a pathway

Within my Angular project, I recently made the transition from using query string elements in URLs such as: http://www.whatever.com/products?productName=TheMainProduct&id=234234 To a route-based system like this: http://www.whatever.com/products/The ...

Modify mouse pointer when an object is clicked using JavaScript

Greetings, I am in the process of designing a website for a client. I have encountered a challenge in changing the cursor icon when a user performs a mousedown on an object. There is an image on the webpage When the user clicks on the image, the cursor s ...

Beginning a counter: a step-by-step guide

I am currently utilizing Angular to create a functional counter like so: <button ng-click="order.startOperation(operation)"> <p ng-if="counter.start"></p> </button> When the button is clicked, it triggers a function that initia ...

Exploring Commitments in React

I'm currently navigating the world of promises and finding it challenging to grasp! My main focus right now is setting up an authentication system for my application. RegisterPage The handleSubmit function in my RegisterPage looks like this: handl ...