Petri
Petri

Reputation: 37

onload event firing before the content is loaded

I'm trying to make my img-wrapper height to be 80 % of its width. The code below fires and works properly when I'm resizing the window, issue is that the function won't get the correct width value. Instead the width is taken to be 100 and thus the height is calculated as 80px.

The site is using bootstrap and I'm trying to make cards that look somewhat like a polaroid picture. The image wrapper needs to have a standard width to height ratio and the image itself needs to be contained within the wrapper but I can't be sure if the images will have the right width:height ratio.

The nearly-working JS:

fixSize = function() {
    $('.card-img-wrapper').each(function() {
        width = $(this).width();
        height = width * 0.8;
        $(this).height(height);

        // Hiding the loader wheel
        $(".loader").hide();

        // Showing hidden elements to avoid flickering and resizing
        $(this).parent().removeClass("hide");
    });
}

$(window).on('load', fixSize);
$(window).resize(fixSize);

HTML

<!-- This is within PHP foreach loop -->
<div class="col-md-4">
    <a class="float-left wh100" href="p_info.php?pID=<?php echo($p['ID']); ?>">
        <div class="card hide">
            <div class="card-img-wrapper">
                <img src="<?php echo($p['imagepath']); ?>">
            </div>
            <h3><?php echo($p['name']); ?></h3>
            <p>Price: <?php echo($p['price']); ?> €</p>
        </div>
    </a>
</div>

CSS

/* Helper Classes */

.float-left {
    float: left;
}

.wh100 {
    width: 100%;
    height: auto;
}

.hide {
    visibility: hidden;
}


/* Card */

.card {
    width: 100%;
    margin-bottom: 30px;
    padding: 30px;
    overflow: hidden;
}

.card-img-wrapper {
    width: 100%;
    height: 25vh;
}

.card-img-wrapper img {
    width: auto;
    height: auto;
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;
}

Upvotes: 1

Views: 295

Answers (2)

Neo
Neo

Reputation: 3399

Wrap your fixSize function in the jQuery document ready function.

$( document ).ready(function() {
     $(window).resize(fixSize);
});

Upvotes: 1

clemlatz
clemlatz

Reputation: 8063

I think the resize function, and thus your fixSize function might be called immediately at page load, before your content is loaded. Try this instead.

$(window).on('load', function() {
    fixSize();
    $(window).resize(fixSize);
});

As @mister-positive suggests wrapping your code in a document ready function might be a good idea too.

Upvotes: 0

Related Questions