18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>JavaScript</strong> in the Browser<br />

<br />

<br />

<br />

Here, the tag is used to create a button that calls sayHi() when clicked. The onclick<br />

attribute specifies an event handler, which is the code that responds to a given event. Events and event<br />

handlers are discussed further in Chapter 9, “All about Events.”<br />

Note that <strong>JavaScript</strong> begins running as soon as the page begins loading, so it is possible to call function<br />

that doesn’t exist yet. In the previous example, you can cause an error by placing the original<br />

tag after the function call:<br />

<br />

<br />

Title of Page<br />

<br />

<br />

<br />

sayHi();<br />

<br />

This is the first text the user will see.<br />

<br />

function sayHi() {<br />

alert(“Hi”);<br />

}<br />

<br />

<br />

<br />

This example causes an error because sayHi() is called before it is defined. Because <strong>JavaScript</strong> is loading<br />

top-down, the function sayHi() does not exist until the second tag is encountered.<br />

Be aware of this problem and, as mentioned previously, use events and event handlers to call your<br />

<strong>JavaScript</strong> functions.<br />

To hide or not to hide<br />

When <strong>JavaScript</strong> was first introduced, only one browser supported it, so concern arose over how the<br />

nonsupporting browsers would deal with the tag and the code contained within. To that<br />

end, a format was devised to hide code from older browsers (which is a phrase that can still be found in<br />

the source code of a great many <strong>Web</strong> sites on the Internet today). The following method uses HTML<br />

comments around inline code so that other browsers won’t render the code to the screen:<br />

<br />

<br />

The first line begins an HTML comment immediately after the opening tag. This works<br />

because the browser still considers the rest of that line as part of HTML, with <strong>JavaScript</strong> code beginning<br />

129

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!