0

I am working on a website.

At some point, I need to replace the background-image of a div with a photo. However, this takes about 5 seconds, so I want to show and hide a loading screen while this process gets completed. I tried:

function changeBackgroundImage(imageURL) {
    showLoadingScreen();
    $("#imagePlaceholder").css('background-image', imageURL);
    hideLoadingScreen();
}

But hideLoadingScreen() is executed before the jQuery css happens.

I'd like to add hideLoadingScreen() as a callback of jQuery css instead. Is this possible?

Here are my other 2 functions:

function showLoadingScreen(){
    $('#pleaseWait').removeClass('hidden');
    console.log('show loading');
}

function hideLoadingScreen(){
    $('#pleaseWait').addClass('hidden');
    console.log('hide loading');
}
3
  • .css() has no callback function . Commented Feb 25, 2014 at 16:36
  • I've never used it but jquery has a when() function which I believe basically allows you to attach an arbitrary method to any time consuming method. link Commented Feb 25, 2014 at 16:40
  • @user3334690 The time-consuming method has to return a deferred or promise, or something that implements the promise interface.. .css() does not. Commented Feb 25, 2014 at 16:43

2 Answers 2

1

You might try loading the image in a hidden img first so you can listen for the load event:

function changeBackgroundImage(imageURL) {
    showLoadingScreen();
    $('<img/>').load(function () {
        $("#imagePlaceholder").css('background-image', imageURL);
        hideLoadingScreen();
        $(this).remove();
    }).attr('src', imageURL);
}
Sign up to request clarification or add additional context in comments.

2 Comments

as my code stands now, in reference to the first chunk of code in my question: do the three procedures inside the first function run at the same time, or only one-after-the-other? I believe what I'm asking is sync or async?
It is sync, except that it won't wait for the browser to load the background image. It will assign the css value synchronously, but not wait for the image to be loaded before moving on.
0

css() doesn't have a callback function. However you can use animate() instead by setting the time to 0:

function changeBackgroundImage(imageURL) {
    showLoadingScreen();
    $("#imagePlaceholder").animate({
        background-image: imageURL
    }, 0, function() {
        hideLoadingScreen();
    });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.