9

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

gabitzish
  • 9,535
  • 7
  • 44
  • 65

4 Answers4

27

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>");
gabitzish
  • 9,535
  • 7
  • 44
  • 65
  • 1
    Here's a simplified version. Modify as required. `$("head").prepend("");` `$("#url").css("font-family", "customFont");` – Zei Jul 29 '20 at 11:06
4

I found a good solution using fontface plugin for jquery. http://www.sitepoint.com/the-fontface-jquery-plugin/

gabitzish
  • 9,535
  • 7
  • 44
  • 65
2

You will need to add some CSS to your style sheet - You can find the right CSSS to add here: How do I load external fonts into an HTML document?

You can then change the font name with whatever its called eg:

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

EDIT: What would be better is to add a class in your stylesheet for the

tag and then add that class to to your p with jquery

p.example{ font-family:Arial, Helvetica, sans-serif; }

$("<p>").addClass("example");
Community
  • 1
  • 1
472084
  • 17,666
  • 10
  • 63
  • 81
1

Personally I use cufon.

Works on 99% of browsers out there!

http://cufon.shoqolate.com/generate/

Enjoy!

Graeme Leighfield
  • 2,825
  • 3
  • 23
  • 38