Log in / Register

Login to your account

Remember Me

Create an account

Fields marked with an asterisk (*) are required.
Reload Captcha

Script for dynamic loading of Google fonts.

Rate this item
(1 Vote)

Простой Javascript подгружающий Google шрифты по мере необходимости в данном по изменению поля <select>.

Наша HTML разметка:

<div>
    <span>Select font:</span>
    <select onchange=fontSelected(event)>
        <option value="Prosto+One">Prosto One</option>
        <option value="Marck+Script">Marck Script</option>
        <option value="Tinos">Tinos</option>
        <option value="Ubuntu">Ubuntu</option>
        <option value="Ubuntu+Condensed">Ubuntu Condensed</option>
        <option value="Ubuntu+Mono">Ubuntu Mono</option>
        <option value="Underdog">Underdog</option>
        <option value="Viaoda+Libre">Viaoda Libre</option>
        <option value="Vollkorn">Vollkorn</option>
        <option value="Vollkorn+SC" selected="selected">Vollkorn SC</option>
        <option value="Yanone+Kaffeesatz', sans-serif">Yanone Kaffeesatz</option>
        <option value="Yeseva+One">Yeseva One</option>
        <option value="Jura">Jura</option>
        <option value="Oswald">Oswald</option>
    </select>
    <div>
        <textarea>This is a sample text. Choose a font and I'll upload it!</textarea>
    </div>
</div>

А теперь Javascript

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);
    }
    select.closest('div').querySelector('textarea').style.fontFamily = select.options[select.selectedIndex].innerHTML;
  } else { // default browser font
    select.closest('div').querySelector('textarea').style.fontFamily = null;
  }
}

Пример

Leave a comment