Search code examples
jquerycallbackloadjquery-callback

Callback of a load function jQuery


I want to be able to do the callback of the .load() function when an element has been created - an image element. The code works by loading a new image element by this code:

$('<img />').load(function()
{
    var img = this;
    $('.block-wrap img').fadeOut('slow', function()
    {
        $(this).replaceWith(img);
    });
}).attr('src', loadurl);

But I want to be able to continue when the image has been loaded and replaced. This is how I need it to work:

$('<img />').load(function()
{
    var img = this;
    $('.block-wrap img').fadeOut('slow', function()
    {
        $(this).replaceWith(img);
    });
}).attr('src', loadurl);

$('.block-wrap input.imageheight').val($('.block-wrap img').height());
$('.block-wrap input.imagewidth').val($('.block-wrap img').width());

It returns the first image height (not the image that has been replaced which is a loading spinner image), so I need it to be able to retrieve the image height and width when it has fully loaded into the DOM. Too bad .replaceWith() does not have a callback method, but I cannot use a callback function on the .load() since it will not work due to it's a function that has been passed through the .load() function.


Solution

  • I'm not 100% on this but could you not add a load event to the end of replaceWith? I.E:

    $(this).replaceWith(img).load(function(){
    
       $('.block-wrap input.imageheight').val($('.block-wrap img').height());
       $('.block-wrap input.imagewidth').val($('.block-wrap img').width());
    
    });