4
votes

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?

2
Yes, divide it with window width, than multiply by 100 :) - skobaljic
Thanks! Or I guess I could use $('.textarea')[0].style.fontSize;? - John the Painter
@JohnthePainter that will return "" in some browsers see stackoverflow.com/questions/15195209/… even that will get you pixels. Calculate it like skobaljic suggested - Huangism
You can only retrieve the computed value in px via the DOM, as stated here. (Voted to close, as duplicate) - skobaljic

2 Answers

3
votes

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

0
votes

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