HTML and CSS Reference
In-Depth Information
Save the document and display it in the browser. The prompt box will appear, and you
can type a color name and click the OK button. You should notice the background
color change immediately.
14.8 Introduction to Programming Concepts
Until now, we have used the DOM to access properties and methods for the window
and document. We have also created some simple event handlers. There is another
aspect to JavaScript, which is more like programming. In this section, we'll touch on
just a small part of this to get a feel for the power of using programming concepts and
build on this later to test input on a form.
Arithmetic Operators
When working with variables, it is often useful to be able to do some arithmetic. For
instance, you may be creating a Web page that calculates the tax on a product. Once
the user has selected a product, you can use JavaScript to calculate the tax and write the
result to the document. Table 14.3 shows a list of arithmetic operators , descriptions,
and some examples.
Table 14.3 Commonly used arithmetic operators
Value of Quantity
quantity = 10
quantity = 10 + 6
quantity = 10 - 6
quantity = 10 * 2
quantity = 10 / 2
Programming languages differ greatly in capabilities, but they all have a few things in
common. They all allow the use of variables, and have commands for decision making,
command repetition, and reusable code blocks. Decision making would be used when
different outcomes are required depending on the input or action of the user. In our
Hands-On Practice example we will prompt the user for an age, and illustrate different
messages printed to the document based on the age. Repetition of commands comes in
handy when performing a similar task many times. For instance, it is tedious to create a
select list containing the numbers 1 through 31 for the days of the months. We can use
JavaScript to do this with a few lines of code. Reusable code blocks are handy when
you want to refer to a block of code in an event handler rather than typing many com-
mands in the XHTML tag's event handler. As this chapter is meant as a very brief taste
of some concepts, it is beyond our scope to elaborate further. We will touch on decision
making and reusable code in the Hands-On Practice examples.
Search WWH ::

Custom Search