4

I am trying to change the font size of a text so that it fits the dimension of a dynamic div.

I have found some jquery code which fits the bill, however I can't use jquery in my code and need to convert it into vanilla javascript.

When I run the converted code I receive this error: 'Uncaught DOMException: Failed to set the 'font-size' property on 'CSSStyleDeclaration': These styles are computed, and therefore the 'font-size' property is read-only.'

This is the original jQuery codes I need to convert:

elements = $('.resize')
el = elements[_i]

and:

resizeText = function () {
    var elNewFontSize
    elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px'
    return $(el).css('font-size', elNewFontSize)
  }

And this is my conversion on:

elements = document.getElementsByClassName('resize')
el = elements[_i]

and:

resizeText = function () {
    var elNewFontSize
    elNewFontSize = (parseInt(window.getComputedStyle(el).fontSize.slice(0, -2)) - 1) + 'px'
    window.getComputedStyle(el).fontSize = elNewFontSize
    return elNewFontSize
  }

What am I doing wrong?

4
  • Add ; to line endings first. (probably a mistake copying) Commented Feb 27, 2019 at 21:26
  • @Mikes3ds I'm coding in Vue2.0 and somehow ending my JS with ; generates a syntax error. Commented Feb 27, 2019 at 21:33
  • @Mikes3ds Are you saying semicolons are required to make the code work? Commented Feb 27, 2019 at 21:34
  • Nope, just noticed, not familiar with the VUE js framework Commented Feb 27, 2019 at 21:40

1 Answer 1

4

You need to set the new size to the element's style.fontSize property, and not the computed value that you get from window.getComputedStyle(), e.g.

el.style.fontSize = elNewFontSize;

--

As an aside, and not directly related, there is no reason to have the variable name twice, you can initialize it with the declaration, i.e. instead of:

var elNewFontSize
elNewFontSize = ...

Simply write

var elNewFontSize = ...
Sign up to request clarification or add additional context in comments.

3 Comments

thank you @isapir. on a side note I am running the code both on window.onload and on window.onresize. However on resize doesn't work. Why this is happening?
@Marcello is it on a public page where we can see it? I'm sure that there's a simple explanation
Unfortunately the code is not public. will try to reproduce it in a pen and repost.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.