jQuery in Action
4
CHAPTER 1
Introducing jQuery
manage, but it also gives us the versatility to completely change the stylistic ren-
dering of a page by swapping out different stylesheets.
dering of a page by swapping out different stylesheets.
 Few of us would voluntarily regress back to the days of applying style with 
HTML
 elements; yet markup such as the following is still all too common:
<button
  type="button"
  onclick="document.getElementById('xyz').style.color='red';">
    Click Me
</button>
We can easily see that the style of this button element, including the font of its 
caption, is not applied via the use of the
caption, is not applied via the use of the
<font>
 tag and other deprecated style-
oriented markup, but is determined by 
CSS
 rules in effect on the page. But 
although this declaration doesn't mix style markup with structure, it does mix 
behavior with structure by including the JavaScript to be executed when the button is
clicked as part of the markup of the button element (which in this case turns some
Document Object Model [
behavior with structure by including the JavaScript to be executed when the button is
clicked as part of the markup of the button element (which in this case turns some
Document Object Model [
DOM
] element named 
xyz
 red upon a click of the button).
 For all the same reasons that it's desirable to segregate style from structure 
within an 
HTML
 document, it's as beneficial (if not more so) to separate the behav-
ior from the structure.
 This movement is known as Unobtrusive JavaScript, and the inventors of jQuery 
have focused that library on helping page authors easily achieve this separation 
in their pages. Unobtrusive JavaScript, along with the legions of the jQuery-savvy,
considers any JavaScript expressions or statements embedded in the
in their pages. Unobtrusive JavaScript, along with the legions of the jQuery-savvy,
considers any JavaScript expressions or statements embedded in the
<body>
 of 
HTML
 pages, either as attributes of 
HTML
 elements (such as 
onclick
) or in script 
blocks placed within the body of the page, to be incorrect.
 "But how would I instrument the button without the 
onclick
 attribute?" you 
might ask. Consider the following change to the button element:
<button type="button" id="testButton">Click Me</button>
Much simpler! But now, you'll note, the button doesn't do anything.
 Rather than embedding the button's behavior in its markup, we'll move it to a 
script block in the 
<head>
 section of the page, outside the scope of the document 
body, as follows:
<script type="text/javascript">
  window.onload = function() {
    document.getElementById('testButton').onclick = makeItRed;
  };
  function makeItRed() {
    document.getElementById('xyz').style.color = 'red';