2

I'm trying to add attribute data-size to my parent div.

Here is my code:

var width, height;
$(".galerie img").each(function() {
  width = this.naturalWidth;
  height = this.naturalHeight;
  $(this).parent().attr('data-size', width+'x'+height);
});

I have around 40 pictures on 1 page. On this way, not every of my div get 'data-size'. Sometimes only 1/2 of them, sometimes 1/3 of them or only 5 of them. How can I fix it?

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
Trung Vu
  • 491
  • 4
  • 19

3 Answers3

3

use document.ready in window.load. this is because not every images are loaded properly before each function fires

$(window).on("load", function() {
var width, height;
    $(document).ready(function(){
        $(".galerie img").each(function() {
          width = this.naturalWidth;
          height = this.naturalHeight;
          $(this).parent().attr('data-size', width+'x'+height);
        });
    });
});
Farhan
  • 1,453
  • 2
  • 15
  • 20
  • window onload cannot guarantee all images are loaded – Roko C. Buljan Dec 15 '15 at 19:44
  • @RokoC.Buljan I have seen your answer and it looks pretty good to me. I have used my answer's code in one of my project and it does good there too. but your answer is more logical. – Farhan Dec 15 '15 at 19:47
  • for more reference http://stackoverflow.com/questions/544993/official-way-to-ask-jquery-wait-for-all-images-to-load-before-executing-somethin – Farhan Dec 15 '15 at 19:49
1

Use a new Image() and wait for it's onload

var width,
    height;
$(".galerie img").each(function() {
  var $that = $(this);
  var img = new Image();
  img.onload = function(){
     width = this.naturalWidth;
     height = this.naturalHeight;
     $that.parent().attr('data-size', width+'x'+height);
  });
  img.src = this.src;
});
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
0

I think the problem is that you are triggering the each when the images are not loaded. Maybe you should check if the last one is loaded before doing it

try to check it with something like this:

 if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {

or the imagesLoaded javascript library.

Víctor
  • 3,029
  • 3
  • 28
  • 43