Dynamically load web font

I am new to this web font. I understand that a particular font can be downloaded from a URL and used on a web page.

My question is: is it possible to dynamically load a web font depending on user input? Just a scenario: enter the user type in the text box and select a font name that has not been there yet . Some javascript code is run to dynamically load a web font resource. Is it possible?

+5
source share
1 answer

Try this (for Google web fonts):

<span>Select font:</span> <select onchange=fontSelected(event)> <option value="default">Browser Default</option> <option value="Droid+Sans">Droid Sans</option> <option value="Open+Sans">Open Sans</option> </select> <h1 id="theText">This is a sample text...</h1> function fontSelected(e){ var select = e.target; if (select.selectedIndex > 0) { // web font var fontID = select.options[select.selectedIndex].value; if (!document.getElementById(fontID)) { var head = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.id = fontID; link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'http://fonts.googleapis.com/css?family='+fontID; link.media = 'all'; head.appendChild(link); } document.getElementById("theText").style.fontFamily = select.options[select.selectedIndex].innerHTML; }else{ // default browser font document.getElementById("theText").style.fontFamily = null; } } 

http://jsfiddle.net/zejz2tkp/1/

This code is bassed in this post: http://amirush.blogspot.ro/2013/07/dynamic-loading-of-web-fonts.html

You can also use one of the existing answers: Download external font with javascript and jquery or dynamically load html jquery fonts

+8
source

All Articles