Tyra Pululi
Tyra Pululi

Reputation: 446

jquery set div container height and width depending on image size

I need to set a div height and width according to the first image size within a list of 40 items (all images are the same size). To make it short function works only the first time you load the page, after visiting other pages imgSize will be undefined.

<div id="ulSorList"> 
  <div class="col-lg-4 col-md-6 col-sm-6 col-xs-6 mix">
    <div class="portfolio-list">
      <a href="#">    
          <div class="overlay-block"></div>
          <img src="/img/1.jpg" class="img-responsive">
      </a>
    </div>
  </div>
  <div class="col-lg-4 col-md-6 col-sm-6 col-xs-6 mix">
    <div class="portfolio-list">
      <a href="#">    
          <div class="overlay-block"></div>
          <img src="/img/2.jpg" class="img-responsive">
      </a>
    </div>
  </div>
  ...
  ...
  ...
</div>

Script

$("#ulSorList img:first").load(function() {
  imgSize = $(this);
  $(".portfolio-list a .overlay-block").width( imgSize.width()).height( imgSize.height() );
  alert(imgSize.width());
});

Everything works until you navigate throught the site (new page is loaded).

IT seems like the script is breaking at some point, so I guess that I only need to get the img size of the first list item.

I edited because since i didnt know what could be the problem the question was bad formulated.

Nothing I cant make it work, now it seems like the script isnt breaking and at least I am getting imgSize width, but I am still at the same position. Script wont function after navigaion.

Any ideas?

Upvotes: 2

Views: 1355

Answers (3)

Tyra Pululi
Tyra Pululi

Reputation: 446

I think I solved, may not be the best way but now its working. The problem is that after navigating, the image was already loaded imgSize was returning the height and width before it was placed in the container. I solved this by adding a timeout.

Upvotes: 1

Shubham
Shubham

Reputation: 11

You are using anchor tag in jquery but where it is in the HTML code. That's an error.

$(".portfolio-list>img").load(function() {
var imgSize= $(this);
$(".portfolio-list>.overlay-block").width(imgSize.width()).height(imgSize.height());
});

Upvotes: 0

Dinesh Devkota
Dinesh Devkota

Reputation: 1417

Try this.

$("selector for menu"). on("click", function() {
    var imgSize= $(".portfolio-list a img");
    $(".portfolio-list a .overlay-block").width( imgSize.width()).height( imgSize.height() );
});

Upvotes: 1

Related Questions