Invoke function once, only after JQuery created images are loaded

I've been searching for a solution but all i'm getting is $(window).on("load", fuction(){}) which just loads the html resources. I'm creating a variable amount of images and inserting them in a div with jquery using an each() function after the window is loaded.

$.each(footeradds, function(fad){
    $("<div class=\"footerads\"><img src=\"image" + fad + ".jpg\"/></div>").appendTo(".footer");
});

I need to calculate the width of the container of these images which depends on the amount of images and their width, which they only have after they've loaded.

if i do

$(".footer img").on("load", function() {})

that function is called every time an image loads, and need it to only be called once, after ALL images have loaded.

My question is: how can i invoke a function after images created with jquery are loaded?

Upvotes: 2

Views: 114

Answers (4)

adeneo
adeneo

Reputation: 318212

You could just use a deferred for each image, and $.when to check that all are resolved etc

var p = $.map(footeradds, function(fad){

    var def = new $.Deferred,
        div = $('<div />', {
            'class' : 'footerads'
        }),
        img = $('<img />', {
            on  : {
                load : function() {
                  def.resolve(this);
              }
            },
            src : 'image' + fad + '.jpg'
        });

    $(".footer").append( div.append(img) );

    return def.promise();
});

$.when.apply($, p).then(function(images) {
    // all images loaded
    var images = [].slice.call(arguments);
    // use images here
});

Upvotes: 0

So i ended up using Pratik Bhalodiya's idea and made this:

var footerW = 0;
var fimgs = 0;
$(".footer img").on('load', function() {
    footerW += + $(this).width();
    fimgs++;
    if (fimgs == $(".footerads").length){
        //do stuff here
    }
});

thanks for your help everyone!

Upvotes: 0

Pratik Bhalodiya
Pratik Bhalodiya

Reputation: 744

there is no methods for it but you can do one thing

take a variable A = count all images , then create other variable B = 1 and increment it on every image load and check condition A == B

that condition will true when last image will called .....:)

Upvotes: 2

Shubham Khatri
Shubham Khatri

Reputation: 281726

Turn the event off after first time

$(".footer img").on("load", function() {
    $( this ).off( event );
})

Upvotes: 0

Related Questions