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 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 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?
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];
}
for anyone wondering I needed to clear the fixed height that I set on the resize
function clearHeight(selector) {
$(selector).height('auto');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.