Nicros
Nicros

Reputation: 5183

Calling a function on an image after it is loaded

I am trying to dynamically add a bunch of images to my page in jQuery, and then use the pixastic image processing library to modify them. The user enters some search criteria, the list of image URLs is returned I append them to my content area and then try to do something- invert them for example. Here is my code:

function loadImages() {
$.ajax( {
    type: "POST",
    url: "/reporter/api/ezdz/getslides/",
    data: {
        'startDate': $( "#startdate" ).val(),
        'endDate': $( "#enddate" ).val()
    },
    success: function ( data ) {
        for ( var i = 0; i < data.length; i++ ) {
            var imgname = "imgename" + i;
            $( "#imagecontentarea" ).append( '<img id=' + imgname + ' src="' + data[i].ImageUrl + '" />' );
            $( imgname ).one( 'load', function () {
                $( imgname ).pixastic( "invert" );
            } );
        }
    }
} );
}

The images are returned just fine, and my load event is even fired... but the images don't change.

This code however works fine if I call it from document.ready:

$( "#imagecontentarea" ).append( '<img id="testimg" src="http://localhost/thumbnail.jpg" />' );
$("#testimg").one('load', function() {
    $( "#testimg" ).pixastic( "invert" );
});

I would prefer to operate on each image as it is loaded, rather than wait til they all load then start inverting them. I looked at the imagesloaded library but it looks like that operates on a parent container (?).

Anyways, what am I doing wrong here?

Upvotes: 0

Views: 276

Answers (1)

Barmar
Barmar

Reputation: 781380

Try changing your success function to this:

success: function ( data ) {
    for ( var i = 0; i < data.length; i++ ) {
        var imgname = "imgename" + i;
        $( "#imagecontentarea" ).append( '<img id=' + imgname + ' src="' + data[i].ImageUrl + '" />' );
        (function (imgname) {$( imgname ).one( 'load', function () {
            $( imgname ).pixastic( "invert" );
        } );})(imgname);
    }
}

Your code was not saving imgname in the closure, so you were operating on the last name in the loop.

EDIT: Another possibility is to use a class:

success: function ( data ) {
    for ( var i = 0; i < data.length; i++ ) {
        var imgname = "imgename" + i;
        $( "#imagecontentarea" ).append( '<img class="imagename" id=' + imgname + ' src="' + data[i].ImageUrl + '" />' );
    }
    $(".imagename").one( 'load', function () {
        $(this).pixastic( "invert" );
    } );
}

Upvotes: 1

Related Questions