Ad

How To Fire Resize Event After All Images Resize

- 1 answer

I have a function that is being called on window resize

$(window).resize(setVideoElements);

That function sets the height for a class of videoThumbnail containers

var setVideoElements = function () { setElementsHeight('.videothumbnail'); };

function setElementsHeight(selector) {

    console.log('setting Max element height');

    // Get an array of all element heights
    var elementHeights = $(selector).map(function () {
        return $(this).height();
    }).get();

    // Math.max takes a variable number of arguments
    // `apply` is equivalent to passing each height as an argument
    var maxHeight = Math.max.apply(null, elementHeights);

    // Set each height to the max height
    $(selector).height(maxHeight);
}

The function works fine except for the fact that its firing too quickly

<div class="thumbnail videothumbnail">
  <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="@Url.Action("Video", new { ID = Video.ID })">
    <img class="videoThumbnailImg" src="@Video.ThumbnailUrl" alt="">
  </a>
  <div class="caption">
     <h3>@Video.Name</h3>
     @foreach (var tag in Video.TagsToVideos)
     {
        <span><a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="#">@tag.Tag.Name</a></span>
     }
  <p>@Video.Description</p>
</div>

The issues is that the function is firing before the images are resize. I need to fire the resize function after all of the images have already been resized.

Do anyone know how to fire this function once after all of the images have Resized?

Ad

Answer

The <img> HTML Element has an onload callback. It fires when the image data has finished downloading from its source. Utilise this to make note of when an image is loaded. Count the load events and call setElementHeight once all your images are loaded.

An example could look like the below:

var sources = ['img/a.jpg', 'img/b.jpg', 'img/c.jpg'],
    loaded = 0;

for (var idx in sources) {
  var img = document.createElement('img');
  img.onload = function() {
    loaded++;
    if(loaded === sources.length) {
      setElementHeight();
    }
  }
  img.src = sources[idx];
}
Ad
source: stackoverflow.com
Ad