Trung Vu
Trung Vu

Reputation: 531

jQuery each is too fast

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?

Upvotes: 2

Views: 302

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

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;
});

Upvotes: 1

Farhan
Farhan

Reputation: 1483

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);
        });
    });
});

Upvotes: 3

Víctor
Víctor

Reputation: 3039

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.

Upvotes: 0

Related Questions