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?

Noam Hacker
  • 4,671
  • 7
  • 34
  • 55

3 Answers3

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.

Knu
  • 14,806
  • 5
  • 56
  • 89
  • Thanks, so is there an alternative method for this context? – Noam Hacker Mar 19 '16 at 13:58
  • @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](https://developer.mozilla.org/fr/docs/Web/API/FontFaceSet). – Knu Mar 19 '16 at 14:39
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";
Community
  • 1
  • 1
Danielson
  • 88
  • 1
  • 8
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.

Haibara Ai
  • 10,703
  • 2
  • 31
  • 47