How to get the height of an <img>, divide by 2 and check if its greater than 200 pixel?

I want to perform the following operations for each element on a webpage:

1.) Get the height of it
2.) get 50% of the value
3.) check if the new height is still above 200 pixel
4.) set the new height (if necessary)

Something like

document().get("img").setHeight(max(currimg.getHeight() * 0.5,200));

The command above does nor exist. It should only demonstrate a near-to solution.

How would a real command look like?

  • getElementsByTagName(),
  • foreach
  • .height is a property of img tags. It is read/write.
  • parseInt()
  • Math.max()

Note: Will only work with images whose dimensions are currently measured in pixels.

1 Like

I thought I’d have a crack at this to brush up my JS skills but this is probably too simplistic.:slight_smile:

The problems I see are that if you have set a width (or width attribute) for the image then the image will be squashed unless you change the width to auto for those images. (Or if you already have the images styled with percentages in the css then you will get squashed or stretched images once again.)

If the images need to be a specific width then you will need to use object-fit in css to maintain the aspect ratio.

There are too many ‘ifs’ for a full example but hopefully the demo will be of some use.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.