Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external font with javascript and jquery

I have a < p > element created dynamically with jquery, and I want to style it with a custom font that I have on my hard drive.

Could you sugest me a method to load that font and apply it to this element.

Right now, the object looks something like:

$("<p>").css({ fontFamily : "Arial",
               fontSize: "13px",
               color: "#000"});

I want to replace fontFamily : "Arial" with my custom font.

Thanks, Gabriel

like image 305
gabitzish Avatar asked Sep 02 '11 10:09

gabitzish


1 Answers

This piece of code does all the job:

$("head").prepend("<style type=\"text/css\">" + 
                                "@font-face {\n" +
                                    "\tfont-family: \"myFont\";\n" + 
                                    "\tsrc: local('☺'), url('myFont.otf') format('opentype');\n" + 
                                "}\n" + 
                                    "\tp.myClass {\n" + 
                                    "\tfont-family: myFont !important;\n" + 
                                "}\n" + 
                            "</style>");
like image 162
gabitzish Avatar answered Sep 19 '22 16:09

gabitzish