Search code examples
javascripthtmlcssdomfont-face

Using dom to create @font-face with style tag isn't working properly?


I'm trying to initialize a style tag using the DOM with JavaScript and for some reason the code below doesn't want to work. Basically I have a div for a container (it's the id) and I want the p tag to display text on the div. So far I have this.

<html>
<head>
</head> 
<style>
body
{      
    background-color: black;    
}
#container
{       
    position: relative; 
    margin: 0 auto;     
    height: 100%;
    width: 100%;
    z-index: 1;
}
#p_1
{
    font-family: my_custom; 
    font-size: 50px;   
    color: red;
    z-index: 2;
}
</style>
<script language = "JavaScript">
function initialize_font()
{
    var special_font = document.createElement("style");
    special_font.type = "text/css"; 
    document.body.insertBefore( special_font, container);
    special_font.styleSheet.cssText = "@font-face {" + font-family: my_custom;  src: url('my_custom.TTF'); + "}";   
}
</script>
<body onload = "initialize_font()">
    <div id = "container">                      
       <p id = "p_1">hello</p>
    </div>  
</body>
</html>

Solution

  • You've messed up the quotes and are not creating the style tag the correct way, and styles must be in the head section, and you don't have to wait for an onload event as there's no need for the DOM to be ready to insert the style tag.

    Something more like this

    <html>
        <head>
            <style type="text/css">
                body {      
                    background-color: black;    
                }
                #container {       
                    position: relative; 
                    margin: 0 auto;     
                    height: 100%;
                    width: 100%;
                    z-index: 1;
                }
                #p_1 {
                    font-family: my_custom; 
                    font-size: 50px;   
                    color: red;
                    z-index: 2;
                }
            </style>
            <script type="text/javascript">
                var special_font = document.createElement("style");
                special_font.type = "text/css"; 
                special_font.innerHTML = "@font-face {font-family: my_custom;  src: url('my_custom.TTF');}";   
                document.getElementsByTagName('head')[0].appendChild(special_font);
            </script>
        </head> 
    <script>
    </script>
    <body>
        <div id = "container">                      
           <p id = "p_1">hello</p>
        </div>  
    </body>
    </html>