23.04.2013 Views

javascript

javascript

javascript

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 10 ■ SCRIPTING BOM<br />

function getCookie(name) {<br />

var batch = document.cookie, i, firstCut, secondCut;<br />

i = batch.indexOf(name + "=");<br />

if (i !== -1) {<br />

firstCut = i + name.length + 1;<br />

secondCut = batch.indexOf(";", firstCut);<br />

if (secondCut === -1) secondCut = batch.length;<br />

return decodeURIComponent(batch.substring(firstCut, secondCut));<br />

}<br />

}<br />

Finally, if getCookie() cannot find a cookie named name, let’s convey failure by appending an else<br />

clause that returns false. In just a moment, we will check for false prior to presetting the skin relative to<br />

a visitor’s preference. The final code for getCookie() would be as follows:<br />

function getCookie(name) {<br />

var batch = document.cookie, i, firstCut, secondCut;<br />

i = batch.indexOf(name + "=");<br />

if (i !== -1) {<br />

firstCut = i + name.length + 1;<br />

secondCut = batch.indexOf(";", firstCut);<br />

if (secondCut === -1) secondCut = batch.length;<br />

return decodeURIComponent(batch.substring(firstCut, secondCut));<br />

} else {<br />

return false;<br />

}<br />

}<br />

Setting the User’s Skin Preference<br />

Now for a function to preset the skin to blue, fuchsia, or green depending on the visitor’s preference.<br />

Hmm. Let’s cleverly name it presetSkin(). In its block, declare a local variable named pref, and assign to<br />

it the return value of passing "skin" to getCookie():<br />

function presetSkin() {<br />

var pref = getCookie("skin");<br />

}<br />

So, pref will contain "blue", "fuchsia", or "green" if the visitor set their preference during a<br />

previous visit. Otherwise, pref will contain false. Note that if cookies are disabled, pref will contain<br />

false as well. With this in mind, let’s make sure pref does not contain false before we do anything else.<br />

An if condition and the !== operator will do the job:<br />

function presetSkin() {<br />

var pref = getCookie("skin");<br />

if (pref !== false) {<br />

}<br />

}<br />

Fine and dandy. Now if JavaScript runs the if block, we have a skin to set. Just set the href member<br />

of the skin style sheet to "blue.css", "fuchsia.css", or "green.css" by concatenating pref to ".css":<br />

function presetSkin() {<br />

var pref = getCookie("skin");<br />

403

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

Saved successfully!

Ooh no, something went wrong!