0

I am creating and styling a div using javascript like this:

var div = document.createElement("div");
div.setAttribute('style',  'box-shadow: 10px 10px 50px #888888; \
                            background-color: #ffb734; \
                            etc...
                           ');

I have to do it this way as I am inserting the div from a chrome extension content script.

How can I change the font face, if I have downloaded a font myFont.ttf to the same directory?

Here is what I've tried:

var div = document.createElement("div");
div.setAttribute('style',  'box-shadow: 10px 10px 50px #888888; \
                            background-color: #ffb734; \
                            @font-face {\
                                font-family: '" + 'openSans' + "'; \
                                src: url('" + 'OpenSans-Semibold.ttf' + "') \
                            } \
                           ');

But this breaks the div (it stops showing up)

Thanks in advance!

p.s. Is it a better approach to instead make a css file and include it in my manifest?

3 Answers 3

3

The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces).

That means that at-rules are not allowed in that context.

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

2 Comments

Thanks, so is there an alternative method for this context?
@NoamHacker you can use the font or font-family properties, that's it. If you are limited to javascript solutions, you should probably check the FontFaceSet interface.
0

Are you trying to build a dynamic text box the user can change? If so this answer will guide you through creating one, https://stackoverflow.com/a/8957518/5914723

If not, then here is some JS that will modify a div. You're modifying the HTML DOM with this code, HTML and CSS. https://jsfiddle.net/Dneilsen22/ohodgo7u/

HTML: empty div

<div id="changeMe"></div>

JS

var changeMe = document.getElementById("changeMe");
changeMe.innerHTML = "You can style me too!";
document.getElementById("changeMe").style.font = "bold 40px serif";

Comments

0

font-face should be specified in an external css file, yes, it's a better approach to make a css file and include it in your manifest.

BTW, use + rather than \ to break the string in multi lines. The latter is not preferred.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.