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?
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';
$('.textarea')[0].style.fontSize;
? - John the PainterYou can only retrieve the computed value in px via the DOM
, as stated here. (Voted to close, as duplicate) - skobaljic