Separating Form and Function: JavaScript and HTML

Wherever CSS and Standards are discussed, you'll often hear about separating content from presentation. Meaning (X)HTML for content and CSS for presentation. At the same time as we separate the content and layout, we can also separate out our JavaScript functionality from the main document, for much the same reasons.

In this tutorial we'll look at moving the JavaScript code out of the HTML document, to keep our page sizes down and our code reusable. We'll look at a different way to handle user initiated events via the script, and develop a sample piece of code for clearing a search box into a more reusable piece of code.

$2.79
- OR -

Overview

Clean Code is Good Code

Take a look at the code below, search.htm. It's probably something you've seen before, an HTML search form, and a simple script to clear the contents of a search input the first time the user clicks in it.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset="iso-8859-1"" />
<script type="text/JavaScript">
//set search box to nothing on first focus.
      var set="false;" 

      function clearbox(box){
            if(!set){
                  box.value='';
                  set="true;"
                  }
      }
</script>
<title>Search Form</title>
</head>
<body>
<form name="form1" id="form1" method="post" action="">
  <input name="search" type="text" id="search" onfocus="clearbox(this);" value="Your Search"/>
  <input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>

When the user clicks in the textbox it gains “focus”. This triggers an onfocus event, for which a JavaScript function call has been provided in the XHTML using:

 onfocus="clearbox(this);"

The function has a parameter of this sent to the function, so it knows that it is the search input we will be clearing.

The function is defined in the top of the document inside a <script> tag. When the function is called, if the value of the variable set is equal to false, it clears the searchbox of its default value. We it then sets the variable to true so that the same doesn't happen the next time the user clicks on the search box.

Matt Machell

Matt MachellA man of many talents, Matt has been a web designer, technical editor, and jewellery picker. He is currently on contract for the Birmingham City University, producing pages for research centres.

He has tech-edited a dozen books on web design and development for glasshaus, Apress and Sitepoint.

He likes music with loud guitars and games with obscure rules.

His website can be found at: http://www.eclecticdreams.com

He lives in Birmingham with his girlfriend, Frances, and a horde of spider plants.

See All Postings From Matt Machell >>

Reviews

Be the first to write a review

You must me logged in to write a review.