Please refrain from initiating the next action until the previous action has been completed

As a beginner, I am currently working on a photo viewer project using JavaScript and jQuery.

My main issue arises when clicking on the arrow to view the next picture. I want the current picture to fade out smoothly before the new one fades in. However, there was a problem where the old picture would still be visible during the fade-in transition if the new image took longer to load. This led me to the conclusion that I need to ensure the fade-in effect only begins once the new picture has fully loaded.

I have come up with a sequence of actions that should run consecutively, with each step triggered only after the previous one has completed:

$('#image').fadeOut(500);
getImage();
$('#image').fadeIn(500);

Here is the function responsible for fetching the new image:

getImage = function() {
    document.getElementById("image").src = "Images/Image" + counter + ".jpg";
}

In this code, 'counter' is a variable previously declared and updated every time the user clicks on the 'next' button or equivalent.

Considering my limited programming knowledge, I am seeking a solution to ensure that:

$('#image').fadeIn(500);

Is not executed until the new image has been successfully retrieved. Otherwise, what happens is that the old image begins fading in before being replaced by the new one.

I attempted to use a callback like this:

$('#image').fadeOut(500, function() {
        getImage();
});

$('#image').fadeIn(500);

However, this approach did not work as intended since it requires nested fallbacks, which I am unsure how to implement.

Another strategy I tried involved checking the status of image loading:

var hasloaded = $('#image').fadeOut(500, function() {
    getImage();
});

if (hasloaded)
{$('#image').fadeIn(500);}

Unfortunately, this clever workaround also proved unsuccessful in solving the issue at hand.

I would greatly appreciate any guidance or assistance in resolving this dilemma.

Thank you.

Answer №1

To implement a JavaScript Image object, simply create the object and set the src to the target element in the load event.

$('#image').fadeOut(500, function () {
    loadImage(function () {
        $('#image').fadeIn(500);
    });
});

loadImage = function (cb) {
    var img = new Image();
    img.onload = function () {
        document.getElementById("image").src = img.src;
        cb();
    };
    img.src = "Images/Image" + counter + ".jpg";
}

Another approach is to utilize the promise() method.

$('#image').fadeOut(500, function () {
    loadImage().then(() => {
        $('#image').fadeIn(500);
    });
});

loadImage = function () {
    return new Promise((resolve, reject) => {
        var img = new Image();
        img.src = "Images/Image" + counter + ".jpg";
        img.onload = function () {
            document.getElementById("image").src = img.src;
            resolve("Success!");
        };
    });
}

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

Vue: Displayed list displaying checked checkboxes

My attempt at displaying the selected checkboxes is as follows: <pre>{{ JSON.stringify(selectedAttributes, null, 2) }}</pre> <ul class="list-unstyled" v-for="category in categories" ...

What is the best way to transfer the value of a slider from jQuery or JavaScript to a Python Flask application

Trying to implement a round slider that displays its value on the client-side webpage. Whenever the user adjusts the slider, the updated value needs to be sent to the server using Python Flask as the backend. I attempted to achieve this using jQuery and Aj ...

Ensure the div element remains fixed at the top of the page

I created a script to identify when I reach the navigation bar div element and then change its CSS to have a fixed position at the top. However, I am encountering an issue where instead of staying fixed, it jumps back to the beginning of the screen and fli ...

Local error when attempting to export a node module

As a novice in node.js, I'm looking to parse an XML file into JSON. To achieve this, I decided to use the bluebutton library available at https://github.com/blue-button/bluebutton.js. After installing the module using npm install bluebutton, a node_m ...

I'm having trouble getting the "spacing" styling attribute to work in Material UI when I attempt to space out elements within my Box component. Can anyone explain why this might be happening?

Within my React 16.10 application, I am utilizing materialUI components. Specifically, I have incorporated two buttons inside a Box element. <Box style={{ marginTop: "3rem", marginLeft: "1rem", display: "f ...

The function SetInterval is invoked multiple times

I am currently working on developing a Tetris game and I have encountered a bug that affects the speed of the game. The issue arises when the function setInterval(move_tetris_part,interval_time); is called multiple times, resulting in an increased downward ...

Getting JSON or JSONP data through a XAMPP local server is a straightforward process

After setting up a local server with XAMPP, my goal is to retrieve JSON / JSONP data from that server. Additional query: Do I need to upload the JSON file directly onto the server? Or can I achieve this using somePHPcoding? If so, which? I have come ac ...

Convert several XML nodes to display in an HTML format

I am currently facing an issue where I am trying to display all the nodes of a specific tag in XML. Although it does filter the data correctly, only one node is showing up. Is there anyone who can assist me with this problem? Below is the XML content: < ...

How to smoothly scroll with jQuery animation without relying on $.browser and preventing double firing

Many inquiries have arisen about the cross-browser functionality of $('html, body').animate();, yet I seem unable to find a solution for this particular issue: I am eager to eliminate $.browser from my code, but I do not want the scroll event to ...

What is the best way to access and read the contents of a text file retrieved via axios?

I am looking to utilize a REST API to read the text from a file. I have been using marked to convert the txt file to markdown and display it in vue.js. However, I am unsure of how to actually retrieve the contents of the file. During my research, I came ...

Ways to adjust text color after clicking on an element

Just a heads up, I didn't write all of the web-page code so I'm not exactly sure what pdiv is. But I want to see if I can fix this small issue [making text color change when clicked on to show which section you're reading]. This particular ...

Maintaining checked items in their original state while searching for another one in ion-searchbar can be achieved by properly handling

My goal is to maintain the checked items as checked when searching for another item in ion-searchbar. While I have managed to keep the checked items, the checkmark icon does not stay checked. What I aim for is to retain the checked state of all food items ...

Sending user input data to a function in a React component

I am currently facing a challenge where I must retrieve the value of an input field in order to initiate an API request. Here is my current setup: import React, { Component } from 'react' import axios from 'axios'; const fetchWeather ...

Sort by characteristics of embedded array - Knockout

I'm struggling with filtering a nested array using Knockout. My goal is to filter the array by both 'tag-names' and 'name'. For example, searching for 'whal' should display all objects that contain a tag with that name ...

Unable to retrieve the 'href' on different pages

Why am I unable to retrieve the "href" from other pages, but still can on the first page? Is there something wrong with it? Will changing the Xpath allow me to get all "href"s from every page? !pip install selenium from selenium import webdriver import t ...

inputting an array of strings into the value attribute of an input element using jQuery

Whenever a user writes something in the input field with id="clientAdd" and presses enter, that text should be displayed as a tag inside a div. These tags are then saved as an array of strings, which I want to pass as the value for the hidden input field w ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

What strategies can I use to control the DOM within the onScroll event in ReactJS?

I am currently working on implementing an arrow-up button that should be hidden when I am at the top of my page and displayed once I scroll further down. However, I am facing issues with manipulating the DOM inside my handleScroll function to achieve this. ...

Preventing event propagation in Angular when clicking

What is the best way to call an Angular function within my jQuery code? I attempted to do so with the following: $(document).on('click', '.myBtn', function(e) { angular.element($(".someClass")).scope().clearBtnItems(); e.stop ...

Using Jquery for AJAX validation

I am currently working on setting up error messages for my form using jQuery. However, when I try to view the form, it only requires the email field to be filled out, even though I have specified that the name field is required as well. Below is the code I ...