Search code examples
javascripthtmlcssgoogle-font-api

Google API fonts in a select box


https://stackoverflow.com/q/5065542/1716774
I like to apply the same function in my Fiddle

HTML

  <select id="styleFont">
          <option value="0">Myraid Pro</option>
          <option value="1">Sans ref</option>
          <option value="2">Times New Roman</option>
          <option value="3"> Arial</option>
 </select>
 <br>
  <textarea id="custom_text"></textarea> 

CSS

 #custom_text{ resize: none;}​

Script

      $("#styleFont").change(function () {
     var id =$('#styleFont option' + ':selected').text();    
    $("#custom_text").css('font-family',id);
    });​

I tried to add the google API fonts in my select box by using

https://www.googleapis.com/webfonts/v1/webfonts?key=YOUR-API-KEY

how to add this to my fiddle


Solution

  • Use a JSONP request and add each returned font to a select:

    function SetFonts(fonts) { 
        for (var i = 0; i < fonts.items.length; i++) {      
         $('#styleFont')
             .append($("<option></option>")
             .attr("value", fonts.items[i].family)
             .text(fonts.items[i].family));
        }    
    }
    var script = document.createElement('script');
    script.src = 'https://www.googleapis.com/webfonts/v1/webfonts?key=API_KEY&callback=SetFonts';
    document.body.appendChild(script);