Search code examples
javascriptjsongoogle-apiwebfonts

how to parse and list down the fonts from google using getJSON


I already have pulled and loaded all font from GoogleAPI

Now what i'm trying to do is to load the fonts on dropdown select change.

The dropdown is the categories of the fonts

Here's the dropdown select list

<select name="pick_font" class="form-input" onchange="change_font_group()">
    <option value="serif">Serif</option>
    <option value="sans_serif">Sans Serif</option>
    <option value="display">Display</option>
    <option value="handwriting">Handwriting</option>
    <option value="monospace">Monospace</option>
</select>

And here's the on change change_font_group()

function change_font_group(){
$(document).ready(function() {
    $.getJSON('https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=AIzaSyD8wNQ45GwEr0bZljjRtP8131v42rrFhac', function(response) {
        alert('json object fetched successfully!');
        alert(response[0]);
    });
})
}

Here's the googleapi

https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=AIzaSyD8wNQ45GwEr0bZljjRtP8131v42rrFhac

And I need to put all those fonts in here

<div class="form-group" id="font_families_list">

</div>

Any idea how to do that?


Solution

  • There is no data in response[0] so you should do something like this to get the list of fonts like this:

    function change_font_group(){
      $(document).ready(function() {
          $.getJSON('https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=AIzaSyD8wNQ45GwEr0bZljjRtP8131v42rrFhac',    function(response) {
            var items = response.items;
            var listElements = '';
            items.forEach(function(item){
              listElements+='<li>' + item.family + '</li>';
            });
            $('#font_families_list').html('<ul>'+listElements+'</ul>');
        });
      })
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=AIzaSyD8wNQ45GwEr0bZljjRtP8131v42rrFhac"></script>
    
    <select name="pick_font" class="form-input" onchange="change_font_group()">
        <option value="serif">Serif</option>
        <option value="sans_serif">Sans Serif</option>
        <option value="display">Display</option>
        <option value="handwriting">Handwriting</option>
        <option value="monospace">Monospace</option>
    </select>
    
    <div class="form-group" id="font_families_list">
    </div>