0

I'm appending divs, and I need to get the image height en width. I need to add css to the MB-Container class, according to the height/width of the image

example: portrait -> container width 100%, landscape -> 'self-align':'flex-end'

$('.MB-Container').append('' +
  '<div class="Cover-Item">' +
    '<img src="' + cover + '" style="width:100%; height:100%;"/>' +
    '</div>' +
  '</div>');

However when trying to get the height and width of the image, I'm getting zero for height:

var itemWidth = $('#item1 .Cover-Item img').width();
var itemHeight = $('#item1 .Cover-item img').height();

How can I add a onload function in the append to check for the image width/height?

I've tried:

$(document).on("load",".Cover-Item img", function() {

}).each(function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)
   console.log($(this).load());
     $(this).load();
});

But this only fires once.

user7637745
  • 965
  • 2
  • 14
  • 27
Elvira
  • 1,410
  • 5
  • 23
  • 50
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – peeebeee Jul 03 '18 at 13:56

1 Answers1

0

The actual onload function is blank in your example. This might work:

$(document).on("load",".Cover-Item img", function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)
   console.log($(this).height());
});
Michael Lorton
  • 43,060
  • 26
  • 103
  • 144