Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check aspect ratio of img via Javascript

I've been asking a css viable solution in this question for a responsive photo gallery with images of different ratios.
Unfortunately i guess it's too complicated to do this via css, so the only fast-easy solution is to use javascript to check the thumbnails aspect ratio and change the css inline for certain thumbs:
the script should check the height:width ratio of every thumbnail, if the ratio is lower than 0.6666666666666667 (2:3) then set via css height:100%; max-width:none; to override the actual rules. Can also be added a class, if easier.

How can this be done via javascript? (jquery can be used too as the library is already present for other plugins).

The structure of the grid is like this:

<ul id="gallery" class="gallery-grid">
  <li class="grid-block">
    <div class="block-wrap">
        <div class="link-wrap">
            <a href="<?php echo $photo->sourceImageFilePath; ?>" class="block-link" target="_blank" >
                <img class="block-thumb" src="<?php echo $photo->thumbImageFilePath; ?>"/>              
            </a>
        </div>  
    </div>
  </li>
</ul>

Ofcourse if you can find a viable css answer to my previous question is even more welcome! thanks!

like image 550
Gruber Avatar asked Oct 28 '12 23:10

Gruber


2 Answers

var ratio = $img.height() / $img.width();
if ( ratio < (2/3) ) { $img.css({ height: '100%', maxWidth: 'none' }) }
like image 130
elclanrs Avatar answered Sep 23 '22 23:09

elclanrs


You might just want to query every thumbnail and do the math.

$('img').each(function(_, img) {
    var $this = $(this);

    if( $this.height() / $this.width() < 0.6666666666666667 ) {
        $this.css({
            height: '100%',
            maxWidth: 'none'
        });
    }
});
like image 33
jAndy Avatar answered Sep 22 '22 23:09

jAndy