Matt
Matt

Reputation: 2327

How to load page only after JavaScript function has finished executing and performed its magic?

Here's the story...

I have an image that is of dimensions 1174px x 660px within a container of dimensions 1174px x 375px. The image's height is cutoff and only 375 pixels worth of the image's height is displayed as I set overflow hidden on the container.

I have created a JavaScript function that takes this image (1174x660) and vertically centers it in its container (1174x 375) so that the center of the image is at the center of the container.

function allFeaturesImagesResize () {
    var allFeatures = function () {
        var image = $('.all-features article img'),
            container = $('.all-features article'),
            container_height = container.height(),
            image_height = image.height(),
            container_center = .5 * container_height,
            image_center = .5 * image_height,
            center = (image_center - container_center);
            image.css('position','relative').css('bottom', center);

    }
    $(function () {
        $(window).resize(function () {
            allFeatures();
        }).resize();
    });
}

I am using a $(document).ready(function() { //... }); wrapper around this function, however, whenever the page loads I can see the function doing its work of moving the image up to the center point. Is there any way to delay the pay load until after this repositioning is complete?

Keep in mind my site is fluid responsive which is why I need to dynamically position the images as I don't know the user's viewport beforehand dimensions (specifically the width).

Upvotes: 0

Views: 330

Answers (1)

Thanh Trung
Thanh Trung

Reputation: 3804

Use load instead of ready event. $(window).load(function(){ ... your code } will tell that the code should be executed only after all images are loaded. ready event will be fired when the DOM is loaded even if the images are not finished loading

Note that you are selecting multiple images $('.all-features article img'). By doing images.height() it will only get the height of the first found image. The same for the line that select multiple container.

Your code should be translate into "For each image found do" : $('.all-features article img').each (function(){...});

Upvotes: 1

Related Questions