webguy
webguy

Reputation: 692

jQuery: get image height + add padding if needed

I have a Bootstrap carousel with images of various heights. I'm want to center the images vertically. I'm trying to get the image height, subtract it from a constant height, and if it is below the constant, assign it padding-top equal to half the difference.

Here's my code:

    $(document).ready(function() {
    $("div.item img").each(function() {
        var maxHeight = 400;
        var imgHeight = $(this)[0].naturalHeight;
        if (imgHeight < maxHeight) {
            topPad = (maxHeight - imgHeight)/2;
            $(this).css("padding-top","topPad + px");
        }
    });
});

The topPad is being calculated correctly, but no CSS is getting added to the images.

Upvotes: 0

Views: 94

Answers (1)

dippas
dippas

Reputation: 60573

you have an issue in this line $(this).css("padding-top","topPad + px");

topPad is a var therefore no "" around the word

and you need to change this from $(document).ready(function() {} to $(window).load(function() {} so the calcs are made when all the images are fully loaded

$(window).load(function() {
  $("div.item img").each(function() {
    var maxHeight = 400;
    var imgHeight = $(this)[0].naturalHeight;
    if (imgHeight < maxHeight) {
      topPad = (maxHeight - imgHeight) / 2;
      $(this).css("padding-top", topPad + "px");
      console.log(topPad, $(this)[0].src)
    }
  });
});
.item {
  display: inline-flex
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item"><img src="//lorempixel.com/100/500" alt=""></div>
<div class="item"><img src="//lorempixel.com/100/300" alt=""></div>
<div class="item"><img src="//lorempixel.com/100/100" alt=""></div>

Upvotes: 1

Related Questions