4

I've set my font sizes using vw but want to retrieve this value in jQuery but when I use $('.textarea').css('font-size'); it returns the px equivalent rather than the vw unit.

Is there any way for it to return the correct stated value?

TylerH
  • 20,799
  • 66
  • 75
  • 101
John the Painter
  • 2,495
  • 8
  • 59
  • 101
  • 4
    Yes, divide it with window width, than multiply by 100 :) – skobaljic Aug 22 '17 at 18:33
  • Thanks! Or I guess I could use `$('.textarea')[0].style.fontSize;`? – John the Painter Aug 22 '17 at 18:33
  • @JohnthePainter that will return "" in some browsers see https://stackoverflow.com/questions/15195209/how-to-get-font-size-in-html even that will get you pixels. Calculate it like skobaljic suggested – Huangism Aug 22 '17 at 18:38
  • `You can only retrieve the computed value in px via the DOM`, as stated [here](https://stackoverflow.com/questions/19404747/get-actual-value-specified-in-css-using-jquery#19404773). (Voted to close, as duplicate) – skobaljic Aug 22 '17 at 18:39

2 Answers2

3

Once you have value in px, multiply it by 100/($(window).width())

For example(in your case):

$('.textarea').css('font-size')*(100/($(window).width()))

Please let me know, if it works

Ashish Balchandani
  • 1,228
  • 1
  • 8
  • 13
0

When using jQuery .css('font-size'), the value returned will always be the computed font size in pixels instead of the value used (vw, em, %, etc). You will need to convert this number into your desired value.

(The following uses a font size of 24px and a window width of 1920px as an example)

To convert the px into vw, first convert the computed font size into a number.

// e.g. converts '24px' into '24'
fontSize = parseFloat($('.textarea').css('font-size'));

Next, multiply this number by 99.114 divided by the window width. (Usually when converting px to vw, you would divide 100 by the window width, however I find the results are slightly incorrect when converting for font sizes).

// returns 1.2389249999999998
fontSize = fontSize * (99.114 / $(window).width());

You can optionally clean up the large decimal returned by rounding to the nearest 100th decimal place.

// returns 1.24
fontSize.toFixed(2)

And now you have the final number you need, just manually add 'vw' where desired.

// returns 1.24vw
fontSize = fontSize + 'vw';

Of course, you can put this all together if you want to shorten your code

// returns 1.24vw
newFontSize = (parseFloat($('.textarea').css('font-size'))*(99.114/ $(window).width())).toFixed(2) + 'vw';
Jirrod
  • 11
  • 4