0

I know this question has been asked a million times before, however I'm trying to do this a different way, a much simpler way because I don't have to support all the major browsers.

For every image on our site, we know the width and the height before runtime as the cdn returns this info for us, once an image registers I basically extract the CURRENT width and figure out the percentage decrease (if any) of that image.

Example:

var originalWidth = 640;
var originalHeight = 480;
var actualWidth = 431;
var decrease = (originalWidth-actualWidth)/originalWidth*100;

Now that I've got the decrease from it's original size, I wanted to do something with the calc css method, seeing as all our images resize proportionally. I've tried this:

$element.css('height', `calc(${originalHeight}px - (${originalHeight}px * ${decrease} / 100 ))` );

I've can't even get this to apply to the element, if I make a much simpler calc css method it works, but this wont even apply, I'm assuming it's because the actual evaluation is failing, but I can't seem to get the units correct

Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
  • I just tested the calc with values and it works. What does your `calc(${originalHeight}px - (${originalHeight}px * ${decrease} / 100 ))` evaluates to after variables been processed? – Asons Apr 23 '17 at 00:30
  • It doesn't maintain the expression, it just outputs `height: calc(326.6px)` @LGSon – Shannon Hochkins Apr 23 '17 at 00:35
  • Well, that will not work, since calc needs minimum 2 values, and it should look something like `calc(200px - (50px * 50 / 100 ))` – Asons Apr 23 '17 at 00:37
  • Maybe if you post a minimal working code sample we could work something out based on what you actually want to achieve – Asons Apr 23 '17 at 00:47
  • What are you trying to do? Can you give us a use case of whatever the end goal is? – Michael Coker Apr 23 '17 at 01:11
  • Basically trying to figure out a way with the calc method to dynamically change the height of an image, before it's loaded, so that by the time it's loaded it doesn't change the viewport height when it renders – Shannon Hochkins Apr 23 '17 at 02:39

1 Answers1

0

Maybe it's only a parenthesis problem, try with this

$element.css('height', `calc((${originalHeight}px - ((${originalHeight}px * ${decrease}) / 100 )))` );
shall
  • 154
  • 9
  • So turns out I was trying to be smart, but this equasion will always return the same result, so it's pointless using the calc method! – Shannon Hochkins Apr 23 '17 at 02:38