04.06.2013 Views

Head First HTML with CSS

Head First HTML with CSS

Head First HTML with CSS

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.

#5 Client-side Scripting<br />

<strong>HTML</strong> pages don’t have to be passive documents; they can also have content that is executable.<br />

Executable content gives your pages behavior. You create executable content by writing<br />

programs or scripts using a scripting language. While there are a quite a few scripting<br />

languages that work <strong>with</strong> browsers, JavaScript is the reigning king. Here’s a little taste of what it<br />

means to put executable content into your pages.<br />

<br />

function validBid(form) {<br />

if (form.bid.value > 0) return true;<br />

else return false;<br />

}<br />

<br />

Here’s a new <strong>HTML</strong> element,<br />

, which allows you to write<br />

code right inside of <strong>HTML</strong>. Notice<br />

we’ve set the type to JavaScript.<br />

And here’s a bit of JavaScript script<br />

that checks a user’s bid to make sure<br />

it’s not zero dollars or less.<br />

Then in X<strong>HTML</strong>, you can create a form that uses this script to check the bid before the<br />

form is submitted. If the bid is more than zero, the form gets submitted.<br />

<br />

Here’s a new attribute in the form<br />

called onsubmit that invokes a script<br />

when the submit button is pressed.<br />

What else can scripting do?<br />

As you see above, form input validation is a common and useful task that is often done <strong>with</strong><br />

JavaScript (and the types of validation you can do go far beyond this example). But that’s just<br />

the beginning of what you can do <strong>with</strong> JavaScript. JavaScript actually has access to the entire<br />

document tree of elements (the same element tree you worked <strong>with</strong> in Chapter 3) and can<br />

programatically change values and elements in the tree. What does that mean? It means you<br />

can have a script change various aspects of your Web page based on a user’s actions. Here<br />

are a few things you might do <strong>with</strong> JavaScript:<br />

n<br />

n<br />

n<br />

n<br />

n<br />

n<br />

Create an interactive game, like a crossword puzzle.<br />

Dynamically change images as the user passes their<br />

mouse over the image.<br />

Set local information in the user’s browser so you can<br />

remember them next time they visit.<br />

Let users choose between different stylings of a page.<br />

Display a random quote from a set of quotes.<br />

Display the number of shopping days before Christmas.<br />

leftovers<br />

you are here 645

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

Saved successfully!

Ooh no, something went wrong!