Check aspect ratio of img via Javascript

11,797

Solution 1

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'
        });
    }
});

Solution 2

var ratio = $img.height() / $img.width();
if ( ratio < (2/3) ) { $img.css({ height: '100%', maxWidth: 'none' }) }
Share:
11,797
Gruber
Author by

Gruber

Updated on June 27, 2022

Comments

  • Gruber
    Gruber almost 2 years

    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!