fala
fala

Reputation: 271

How can I change the height of a element on image load?

I wrote a function to change the height of an element on image load:

$(document).ready(function () {


  $("img").load(function() {
    var width = $(this).width();
    $(".item").height(width*0.85);
  });

The problem is, when I reload my page, sometimes it works and sometimes not. Just randomley somthimes the height is changed and sometimes not. How can I make it always work

The html:

<div class="row row-10 items-grid">
         <div class="col-md-4 col-xs-6">
             <a class="item">
                  <img src="/get/2" alt="">
                  <div class="overlay">
                      <h2 class="">Dogs</h2>
                  </div>
             </a>
          </div>

          <div class="col-md-4 col-xs-6">
            <a class="item" >
                 <img src="/get/3" alt="">
                <div class="overlay">
                <h2 class="uppercase">Cats</h2>
               </div>
            </a>
          </div>
        </div>

Upvotes: 0

Views: 102

Answers (1)

palaѕн
palaѕн

Reputation: 73976

You can try to loop all images and then add image onload event to each one of them individually and when each image is done loading you can update the height of the element which is closest to the image, not all .item elements at once, like:

$(document).ready(function() {
  $('img').each(function() {
    var $this = $(this);
    var img = new Image();
    img.onload = function() {
      var width = $(this).width();
      $this.closest(".item").height(width * 0.85);
    };
    img.src = $(this).attr('src');
  });
});

Upvotes: 1

Related Questions