Jump to content

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


pstein

Recommended Posts

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?

Link to comment
Share on other sites

If you're comfortable with writing more than one line of code, the solution is really simple.

let img = document.querySelector("img"); // Get a reference to the image
let newHeight = img.offsetHeight * 0.5; // Get half of the image's height
if(newHeight < 200) newHeight = 200; // If the value is less than 200 then use 200 instead
img.style.height = newHeight + "px" // Assign a new height to the image

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...