2

I have used css to link to font files in the conventional way, as seen here:

How can I use Google's Roboto font on a website?

However there are a few instances where I may need more complicated style rules, and I use javascript in such cases. Strangely google searches only returned css font link methods, but I'm suspecting js has a way. I got as far as:

d3.select('body').append('text').text('my text')
    .attr('font-family', 'Roboto')
    .attr('src', 'url(my_url) format('truetype')');

However I'm not sure if it's supposed to look like that. Given that it's not working, my hunch is no. Any ideas?

Community
  • 1
  • 1
Arash Howaida
  • 2,575
  • 2
  • 19
  • 50
  • 1
    Have a look here: https://developer.mozilla.org/en/docs/Web/SVG/Tutorial/SVG_fonts – Gerardo Furtado Mar 30 '17 at 05:19
  • I'm not following this: you explicitly asked for a JS solution, **without** CSS, and then you accept an answer that simply says that you have to use CSS? – Gerardo Furtado Mar 30 '17 at 05:58
  • @GerardoFurtado Seeing as that approach doesn't need me to assign classes to be styled, it was elegant enough to work for my use case. A pure js solution would be ideal. – Arash Howaida Mar 30 '17 at 10:15
  • That approach is what everybody does. Actually, it's what even you have been doing, since you said *"I have used css to link to font files in the conventional way"*. Thus, as your question explicitly asks *"can I do this with JS only and without CSS?"*, there are only 2 possible answers: *"no, you can't"*, or a solution with JS. – Gerardo Furtado Mar 30 '17 at 10:50

2 Answers2

0

As long as your referencing your google font in your document like the following:

<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">

All you have to do is specify the name when selecting font-family to apply it to any text element:

d3.select('body').append('text').text('my text')
    .style('font-family', "'Montserrat', sans-serif");

Fiddle - https://jsfiddle.net/7jLgpx68/

# For .ttf files, I would suggest setting it in css first like the following:

@font-face {
  font-family: "Super Sans";
  src: url(#url_to_ttf);
}

and then using it in your js code like

d3.select('body').append('text').text('my text')
    .style('font-family', "Super Sans");
sparta93
  • 3,684
  • 5
  • 32
  • 63
-1

CSS is by far the easiest way to do this. You can always manipulate the tags containing text that you are working with different classes or id's using JS as you need.