Issue with fadein callback malfunctioning when loading json data through ajax

This is a digital portfolio page showcasing various design projects. Upon loading the page, JSON data is fetched using ajax, and one of the keys is utilized to create a list of '.project-links'. The actual project images are not loaded initially, but only when a specific project is selected (refer to the showProj function). I have a query regarding the fadein/fadeout effect: even though the project content is defined/loaded within the fadeOut callback, the images are still being painted onto the screen after the fadeIn animation completes. Can someone provide insights on how to adjust this so that the fadeIn action will wait until the projImages are fully loaded?

Thank you, svs.


        // JavaScript functions and code snippets here...
    

Answer №1

If you want to create a fade out effect for images once they are all loaded, you can add a load event to each image and trigger the fadeOut animation when all images have finished loading.

To keep track of the loading status of multiple images, you can utilize an array of jQuery.Deferred() objects. Once all Deferreds are resolved, you can then initiate the fade animation.

Below is a function that demonstrates how this can be achieved:

function fadeWhenReady(projImages, images) {
    projImages.innerHTML = "";
    var loads = []; //create array for deferred calls

    //create images and set up load events
    for (var i = 0; i < activeProj.images.length; i++ ) {
        var deferred = $.Deferred();
        var img = $("<img src=\"" + activeProj.images[i].url + "\" />");
        img.on("load", function() { deferred.resolve() }); //resolve deferred after image load
        loads.push(deferred.promise()); //add deferred event to the array
        img.appendTo(projImages); //append image to page
    }

    //apply fade effect when all deferreds are resolved
    $.when.apply($, loads).done(function() {
        $("#project-display").fadeTo(600, 1.0); 
    });
}

In your function showProject, remove the call to

$("#project-display").fadeTo(600, 1.0);
and replace it with a call to the fadeWhenReady function as shown below:

projImages.innerHTML = "";
for (var i = 0; i < activeProj.images.length; i++ ) {
    projImages.innerHTML += "<img src=\"" + activeProj.images[i].url + "\" />";
}

P.S. It appears you are using a combination of jQuery and vanilla JavaScript. Consider replacing your XMLHttpRequest calls with jQuery.ajax() for consistency.

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

Using jQuery Ajax to send an associative array with keys containing spaces to PHP in a unique way

My challenge lies in passing my keys correctly to my PHP server. Here is a snippet of the code I am working with: ajax: { url: "<?= base_url("items/getTableData") ?>", type: "POST", dataType: "json", ...

Having trouble loading this JSON data into my table

So I have a little challenge on my hands: I've got a JSON file with information about various books, each including details like title, author, and year of publication. The goal is to select an option from the list and display the chosen property in ...

Validating an email address without the "@" symbol or if the "@" symbol is the last character

I've been working on validating email addresses using regex, but I'm encountering an issue. The problem is that the validation fails for emails that don't contain the "@" character or have it at the end of the word. For example, if I type "a ...

Remove hidden data upon moving cursor over table rows after a delay

Hey there! I'm in need of a little assistance, so I hope you can lend me a hand. Here's the scenario: Within my category table, there are numerous rows, each containing a hidden textbox with an empty value and a unique ID. As users navigate t ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

How can I empty the value of a UI widget (such as an input field, select menu, or date picker) in Webix UI?

Is there a way in Webix UI to clear widget values individually, rather than collectively based on form id? I'm looking for a method using a mixin like $$(<form-id>).clear(). I need control of individual elements, so is there a proper way to res ...

Implement a JavaScript function that loads fresh content onto the webpage without the need to refresh the

$("span.removeFromCart").on("click",function(){ var id = $(this).attr("data-id"); $.ajax({ type: "GET", url: "ajax.php?id="+id+"&action=remove" }) .don ...

Creating a dynamic header in a Bootstrap4 datatable with scroll search and pagination functionality

I've been attempting to create a Datatable using JSON Data with a dynamic header instead of a static one, but I haven't had much success. I want to display the table within a div element only, rather than using the traditional table tag, as it lo ...

Enabling Multi-Row Form Submission in jQuery: Ensure Submit Button is Disabled Until Every Row Has a Checked

I am dealing with a multi-row form that contains single choice radio buttons in each row. My goal is to have the final <button> tag disabled until a radio button has been checked in each row. Although I have found a solution from a previous question ...

Vue router is unable to verify the user's authentication

I have certain app routes that are supposed to be restricted to admins only. I've added requiresAdmin: true, to the meta of those routes, but for some reason it doesn't prevent other users from accessing them. Code Note: I've included comme ...

Executing an AJAX function within each iteration of a foreach loop without the need for a submit button

I'm quite new to PHP/CodeIgniter and I apologize if my issue seems basic or beginner-level to you. My goal is to send values to an AJAX function and print results for each iteration of a foreach loop without using a submit button. Here's the AJA ...

Acquiring the URL from the ajax response with EmberJS

Seeking assistance on extracting the URL from an Ajax response within Ember. This is necessary for handling a particular scenario where the server redirects to a different URL and provides data from the new URL (302 redirect). By capturing the URL from th ...

Unraveling a stringified string in JAVA

I have a string that looks like this: {"version":"T2"} I retrieved this string from a webview and stored it in a variable called s. I am trying to extract the value of the 'version' key. Here is my code: try { s = s.replaceAll(" ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...

Refreshing a DataTable by recreating it with a VueJS-populated HTML table

I am retrieving data from a database using Ajax and presenting it in an HTML table with the help of VueJS. Users can add, edit, and delete rows without any issues. However, I face a challenge when trying to incorporate a DataTable to provide users with th ...

Transform the Angular function into a factory and take advantage of caching

My query differs from others with a similar title. I am attempting to transform a function into a factory in order to share data across controllers, but unlike my other factories, this one is not functioning as expected. I have successfully implemented ot ...

Controller receiving incomprehensible response from service

Here is my service code: 'use strict'; app .service('myService', function($http) { this.getJSON = function() { return $http.get('someUrl/dataForm').then(function(data){ return dat ...

``Is it possible to iterate through a collection of objects using a loop?

I am facing an issue with updating a global array that contains objects, where each object includes another array. My goal is to update the main array with values from the arrays within the objects following a specific logic! generalArray = [{name:String, ...

Vuetify's Handy Helper Classes

Hey everyone, I'm working on a vuetify project and I need to convert inline styles to utility classes (if possible) font-size: 24px; font-weight :600 I checked the documentation and noticed that it only provides options for setting size and weight wi ...

Utilizing Express.js for setting up routes with a default path

In the code snippet below, I am utilizing Express.js: router = express.Router() fs.readdirSync('./controllers').forEach(function (file) { if(file.substr(-3) == '.js') { route = require('./controllers/' + file); ...