Getting Started with JavaScript


It’s time to get started writing some JavaScript. To write JavaScript, you use the <script> element in a Web page like this:

 <html>   <head>     <title>A first JavaScript example</title>     <script language="javascript">         .         .         .     </script>   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

Note that the <script> element is an element much like any other HTML element; it even has an attribute, the language attribute, which in this case you set to "javascript"-including in the Internet Explorer The actual JavaScript code you write goes into the <script> element, and the <script> element usually goes into the <head> section of a Web page.

So what can you do for a first JavaScript example? How about writing a message to the Web page? That sounds like a fine idea. The next question is, of course, how do you access the Web page from inside your JavaScript code?

It turns out that you access the Web page and the browser itself from JavaScript with a variety of built-in objects. The objects available for your use include objects like the document object (which refers to a Web page), the windowobject (which refers to the browser window), and the history object (which refers to a history list that lets the browser navigate forward and backward).

Each of these objects has methods and properties. You can call a method to make something happen (like writing to a Web page) and set the value of a property to configure those objects (like setting the background color of a Web page). Following are a few useful object methods:

  • document.write lets you write text to the current Web page.

  • history.go moves the browser to a page in the browser’s history.

  • window.open opens a new browser window.

And here are a few of the useful properties that are available:

  • document.bgcolor holds the background color of the current page.

  • document.fgcolor holds the foreground color of the current page.

  • document.lastmodified holds the date the page was last modified.

  • document.title holds the title of the page.

  • location.hostname holds the name of the page’s host.

  • navigator.appName holds the type of the browser.

So what does that do for us in the attempt to write to a Web page from JavaScript? You can use the document.write method to do just that. Here’s what it looks like in JavaScript, in the code file first.html:

 <html>   <head>     <title>A first JavaScript example</title>     <script language="javascript">       document.write("You are using JavaScript");     </script>   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

That’s it, just a single line of JavaScript, designed to write the text “You are using JavaScript” to the Web page. This line of code is executed as soon as the browser encounters it, while it’s loading the Web page. The browser encounters the <head> section of this page before the <body> section, which means that you get the result you see in Figure 2.3, where the text written by your JavaScript (“You are using JavaScript”) in the <head> section of the page comes before the header (“A first JavaScript example”) from the <body> section of the page.

image from book
Figure 2.3: A first JavaScript example

Now you’ve written to a Web page using a single line of JavaScript. Note that this JavaScript statement ends with a semicolon:

 <script language="javascript">   document.write("You are using JavaScript"); </script>

All JavaScript statements end with a semicolon like this one does, which is something you have to keep in mind when you’re writing JavaScript.

Fixing errors

What if, in one’s eagerness to get a program done, one made a programming error? Take a look at this version of the previous example. Can you spot the error?

 <html>   <head>     <title>A first JavaScript example</title>     <script language="javascript">       document.writ("You are using JavaScript");     </script>   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

If you saw that document.write was incorrectly written as document.writ, you’re correct. Because the document object doesn’t have a method named writ, no browser is going to be able to run this example. However, the way various browsers handle this issue differs by browser, and that means the tools each browser offers to fix the problem differ.

Internet Explorer gives you the display shown in Figure 2.4. All you see is the <h1> heading in the <body> element-no output from JavaScript.

image from book
Figure 2.4: A JavaScript error in Internet Explorer

Note in particular the small icon in the lower left corner in the Internet Explorer window, which shows a triangle with an exclamation point. That’s Internet Explorer’s way of indicating that there’s a JavaScript problem. Double-clicking that icon opens a dialog box, as shown in Figure 2.5.

image from book
Figure 2.5: Examining a JavaScript error in Internet Explorer

You can see that the error message in Figure 2.5 says, “Object doesn’t support this property or method” and indicates the correct line number. Examining your code with this information lets you correct the problem.

Looks like Internet Explorer is going to be helpful debugging JavaScript, right? Unfortunately, it’s not. The error message you see in Figure 2.5 is about the only one Internet Explorer displays. Even if your JavaScript is so fouled up that none of it can run, you’re still only going to get “Object doesn’t support this property or method.”

Ajax developers deserve better, and there is better available in Firefox, the alternative to Internet Explorer. You should have Firefox on hand as you develop your Ajax applications, not just because many people use Firefox and so you should develop for that browser in addition to Internet Explorer, but because of its excellent debugging help. Firefox really tells you what’s wrong with your script, whereas Internet Explorer only leaves you scratching your head.

This example is shown in Firefox in Figure 2.6. As the figure shows, you’re not getting the results you expected; nothing has been written to the browser window using JavaScript.

image from book
Figure 2.6: A JavaScript problem in Firefox

How can you determine the problem? Select Tools image from book JavaScript Console to open the JavaScript console, as shown in Figure 2.7.

image from book
Figure 2.7: Examining a JavaScript problem in Firefox’s JavaScript console

The JavaScript console is a very useful tool because unlike Internet Explorer, it’s been written to really pinpoint problems and to tell you about them. As you see, the error message here pinpoints document.writ as the problem.

If you’re going to be developing lots of JavaScript-and which Ajax developer doesn’t?-it’s a good idea to get Firefox running on your machine. Doing so can make the debugging process much, much easier.

Commenting your code

As with most programming languages, you can also add comments to your JavaScript scripts. A comment is human-readable text that annotates your code. In JavaScript, you can use \\ to start a comment, and adding comments to your code makes it easier for people to understand what’s going on in that code.

For example, to add the comment “Use document.write to display a message” to your first script, you could do this:

 <html>   <head>     <title>A first JavaScript example</title>     <script language="javascript">       //Use document.write to display a message       document.write("You are using JavaScript");     </script>   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

You can also create a comment at the end of a line using //, like this:

 <html>   <head>     <title>A first JavaScript example</title>     <script language="javascript">       document.write("You are using JavaScript"); //Display          message     </script>   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

There’s another kind of comment in JavaScript, the /* */ comment, which lets you divide a comment up over multiple lines. When the browser sees /* in your script, it stops reading until it encounters */, no matter how many lines that takes. In other words, // is for single-line comments, and /* */ is for multi-line comments. Here’s an example:

 <html>   <head>     <title>A first JavaScript example</title>      <script language="javascript">       /* Use document.write          to display          a message */       document.write("You are using JavaScript");     </script>   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

The // marker prevents the browser from reading any more text from that point to the end of the line, so feel free to sprinkle your code with comments.

Putting your code in external script files

Here’s another JavaScript skill you’re going to need in this book and when you work with Ajax: placing your JavaScript code in external JavaScript files. Here’s how it works: simply place your JavaScript code, which is this single statement here:

 document.write("You are using JavaScript");

in a separate script file named, for example, script.js.

Note 

JavaScript files have the extension .js.

Then you can refer to script.js and include it in your Web page using the <script> element’s src attribute, like this:

 <html>   <head>     <title>A first JavaScript example</title>     <script language="javascript" src="/books/1/252/1/html/2/script.js">   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

That’s all it takes. Now you can store your JavaScript in external files, which is great if your JavaScript is getting long and/or you want to share it between Web pages. As you’re also going to see in this book, there are many Ajax frameworks available for free online. Such frameworks do the Ajax programming for you, saving you lots of time and effort, and those frameworks are usually external JavaScript files.

Responding to browser events

So far, the code you’ve written runs when the Web page containing it loads. That’s because the code is simply stored in a <script> element:

 <html>   <head>     <title>A first JavaScript example</title>     <script language="javascript">       document.write("You are using JavaScript");     </script>   </head>   <body>     <h1>A first JavaScript example</h1>   </body> </html>

Code like this that is simply placed directly in a <script> element executes immediately when a Web page loads. But that’s not the way Ajax applications work. They usually wait until the user does something: clicks a button, types something, and so on. They do that by responding to user events.

An event occurs when something happens in the browser: the mouse moves or is clicked, a scroll bar is scrolled, a button is pressed, and so on. When an event occurs, your JavaScript code can be notified of the event, which means that your code can respond to that event appropriately.

What events are available? Here are some common events you might see in Ajax applications:

  • onabort: Happens when an action is aborted.

  • onblur: Happens when an element loses the input focus.

  • onchange: Happens when data in a control, like a text field, changes.

  • onclick: Happens when an element is clicked.

  • ondblclick: Happens when an element is double-clicked.

  • ondragdrop:Happens when a drag-drop operation is undertaken.

  • onerror: Happens when there’s been a JavaScript error.

  • onfocus: Happens when an element gets the focus.

  • onkeydown:Happens when a key goes down.

  • onkeypress: Happens when a key is pressed and the key code is available.

  • onkeyup: Happens when a key goes up.

  • onload: Happens when the page loads.

  • onmousedown: Happens when a mouse button goes down.

  • onmousemove: Happens when the mouse moves.

  • onmouseout: Happens when the mouse leaves an element.

  • onmouseover: Happens when the mouse moves over an element.

  • onmouseup: Happens when a mouse button goes up.

  • onreset: Happens when the user clicks a Reset button.

  • onresize: Happens when an element or page is resized.

  • onsubmit: Happens when the user clicks a Submit button.

  • onunload:Happens when a page is unloaded.

These are event attributes that you use with HTML tags. How does that work? For example, the document itself is represented by the <body> element, so you can use an attribute like onmousedown to catch when a mouse button is pushed.

So how do you put all this to work? Here’s a simple example, making use of the fact that you can create inline scripts in JavaScript-that is, short scripts that you can assign to an event attribute like onmousedown, no <script> element needed. This example uses JavaScript to display a dialog box called an alert box with the text “You clicked the page” in it:

 <html>     <head>         <title>             Using JavaScript events         </title>     </head>     <body onmousedown="alert('You clicked the page.')">         <h1>             Clicking this page will display an alert box.         </h1>         Give it a try.     </body> </html>

This example works this way: the user presses the mouse button, and the onmousedown event occurs, which executes any code connected to that event. In this case, the JavaScript that executes is alert('You clicked the page.'), which displays an alert box as shown in Figure 2.8.

image from book
Figure 2.8: Handling an onmousedown event

One thing to note about inline scripts like this: Because you assign them to event attributes like onmousedown, you have to enclose them inside quotation marks. If you have to use quotation marks in your code itself, make them single quotation marks, like this:

 <body onmousedown="alert('You clicked the page.')">

Why single quotation marks? JavaScript can handle both single and double quotation marks, and that allows you to alternate them if needed. In other words, this is legal JavaScript:

 alert('You clicked the page.')

and so is this:

 alert("You clicked the page.")

That means you can enclose inline JavaScript inside double quotation marks if you alternate double and single quotation marks. For example, if you used all double quotation marks like this:

 <body onmousedown="alert("You clicked the page.")">

JavaScript would get confused. Where does the quotation begin and where does it end? For that reason, alternate double and single quotation marks like this:

 <body onmousedown="alert('You clicked the page.')">

Okay so far, but inline scripts are designed for very short pieces of code. What if you wanted to connect an event attribute like onmousedown to code in a <script> element? For that, you have to use JavaScript functions.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

Similar book on Amazon
HTML, XHTML, and CSS Bible
HTML, XHTML, and CSS Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
PHP and MySQL Web Development (4th Edition)
PHP and MySQL Web Development (4th Edition)

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net