04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: The Document Object Model<br />

Loading styles via an external file is asynchronous, so the styles will load out of order with the JavaScript<br />

code being executed. Typically it ’ s not necessary to know when the styles have been fully loaded; however,<br />

there are some techniques to accomplish this using events. These techniques are discussed in Chapter 12 .<br />

The other way to define styles is using the < style > element and including inline CSS, such as this:<br />

< style type=”text/css” ><br />

body {<br />

background-color: red;<br />

}<br />

< /style ><br />

Logically, the following DOM code should work:<br />

var style = document.createElement(“style”);<br />

style.type = “text/css”;<br />

style.appendChild(document.createTextNode(“body{background-color:red}”));<br />

var head = document.getElementsByTagName(“head”)[0];<br />

head.appendChild(style);<br />

This code works in Firefox, Safari, Chrome, and Opera, but not in IE. IE treats < style > nodes as special,<br />

similar to < script > nodes, and so won ’ t allow access to its child nodes. In fact, IE it throws the same<br />

error as when you try to add a child node to a < script > element. The workaround for IE is to access the<br />

element ’ s styleSheet property, which in turn has a property called cssText that may be set to CSS<br />

code (both of these properties are discussed further in the next chapter), as this code sample shows:<br />

var style = document.createElement(“style”);<br />

style.type = “text/css”;<br />

try{<br />

style.appendChild(document.createTextNode(“body{background-color:red}”));<br />

} catch (ex){<br />

style.styleSheet.cssText = “body{background-color:red}”;<br />

}<br />

var head = document.getElementsByTagName(“head”)[0];<br />

head.appendChild(style);<br />

Similar to the code for adding inline scripts dynamically, this new code uses a try - catch statement to<br />

catch the error that IE throws, and then responds by using the IE - specific way of setting styles. The<br />

generic solution is as follows:<br />

function loadStyleString(css){<br />

var style = document.createElement(“style”);<br />

style.type = “text/css”;<br />

try{<br />

style.appendChild(document.createTextNode(css));<br />

} catch (ex){<br />

style.styleSheet.cssText = css;<br />

}<br />

var head = document.getElementsByTagName(“head”)[0];<br />

head.appendChild(style);<br />

}<br />

310

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!