سؤال

I loaded d dynamic list of web fonts offered by the Google Web Fonts service and place it in a select list ,like :

$.get("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyChZeTZ-DzMW-45IUBXUSuBha9MWEiXXtI", 
     {}, function (data) {
     $.each(data.items, function (index, value) {
        $('#fonts').append($("<option></option>")
                   .attr("value", value.family)
                   .text(value.family);
    });

Now what i want is to load each font when user select it from the select list and for this i tried :

$("#fonts").live({ change: function () { 
    $.get("http://fonts.googleapis.com/css?family=" + $(this).val(), {}, 
    function () { alert("font loaded"); }); } });

but unfortunately this is not working can anybody please help me out?

هل كانت مفيدة؟

المحلول

The second get request simply returns the needed CSS to load the webfont.

You should either embed that on the page, or easier add a link tag to the page content that will load the google style.

Then you will also need to set the font-family wherever it's used...

Something like that:

$("#fonts").live('change', function () { 

    $('body').append("<link rel='stylesheet' id='colorbox-css'  href='http://fonts.googleapis.com/css?family=" + escape($(this).val()) +"' type='text/css' media='all' />");

    $('body').css({'font-family':'"'+$(this).val()+'"'})

});



$.get("https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyChZeTZ-DzMW-45IUBXUSuBha9MWEiXXtI",  {}, function (data) {

    $.each(data.items, function (index, value) {
            $('#fonts').append($("<option></option>")
                    .attr("value", value.family)
                    .text(value.family));
                    });


});

Note: escape is also used to generate the url in case it need to be url-encoded

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top