HTML and CSS Reference
In-Depth Information
event attributes of an HTML element
For years, it has been common to write HTML pages with input fields and buttons explicitly attached
to JavaScript event handlers. Here's a typical example:
<input type="button" value="Click me" onclick="handleClick()" />
From a purely functional perspective, there's nothing wrong with this codeā€”it works as expected:
the onclick attribute associates the click action with the handleClick JavaScript function, so that
function then runs whenever a user clicks the button. This approach, however, is largely acceptable
only when you're using JavaScript to spice up simple HTML pages. It becomes unwieldy when the
amount of JavaScript code represents a significant portion of the page or the view.
In a way, unobtrusive JavaScript is the script counterpart of CSS classes. With CSS, you write plain
HTML without including inline style information. Next, designers style elements using CSS classes.
Likewise, for unobtrusive JavaScript, you avoid using the in-tag event handler attributes ( onclick ,
onchange , onblur , and the like) and instead use a single JavaScript function to attach handlers when
the page is ready for display. By not using event attributes, you keep markup code and JavaScript
code separated.
What about the code that is referenced by event handlers? In other words, where would you get
the code for functions like handleClick ?
embedded JavaScript code
You can embed JavaScript content in an HTML page in a number of ways. The simplest way to have
JavaScript code ready to use in an HTML page is placing it in the page within a SCRIPT element.
<script type="text/javascript">
...
</script>
As browsers encounter one of these <script> sections, they stop page rendering, execute the
script, and then proceed. If the script element doesn't contain immediate code to execute (for
example, suppose it contains only function declarations), then the browser simply takes note of the
function and proceeds. A script element is therefore an acceptable place to embed the definition of
functions invoked by event handlers.
Embedding script code in a page has both pros and cons, but mostly cons. Table 4-3 summarizes both.
Search WWH ::




Custom Search