HTML and CSS Reference
In-Depth Information
Figure 5.3: three buttons using JavaScript onclick handler attributes
In Example 5.3, the irst button is given an onclick attribute with the value
location = this.value; and the URL is set in the value attribute. this is a spe-
cial JavaScript variable that always refers to the document element in question.
Putting the URL in an attribute separate from the JavaScript command in the
onclick attribute makes it easier for other scripting components on the page
to read and reset the URL. It also provides a little more information to robots,
which are disinclined to scan event handlers and have distaste for JavaScript in
he Random Search Engine button works by calling the function
goToRandomURL() , which uses JavaScript's built-in random-number generator
to choose a link from the array of URLs deined just above the function's
deinition. Using a function in an event-handling attribute allows the same
code to be called from anywhere. Although the math in this function looks
a bit complicated, it is just an expression for converting the output of the
random-number generator, a real number between 0 and 1, to an integer
between 0 and the number of items in the array minus 1. (JavaScript arrays
start with the index 0.)
he third button's onclick attribute contains an expression that closes the
active window. self is another special JavaScript variable that refers to the cur-
rent document window. To enable this “Go Away!” button, all that is needed
is another button (or any element, for that matter) on the page with an event
handler that sets the disabled status to false . he JavaScript expression for
resetting the button is
getElementById('btn3').disabled = false;
Why use buttons at all for links if it is possible to use CSS to make an
anchor element look and act just like a button? he answer is that a button
element is generated by the operating system's graphical user interface (GUI)
instead of by the browser. It has a built-in set of behaviors that simulate the
efect of a physical button. In other words, clicking a button is a more deini-
tive action than clicking a link. Also, buttons can be easily disabled and
Search WWH ::

Custom Search