Client-Side Scripting with JavaScript


Part 2 - Using JavaScript in Web Pages

How to Use JavaScript

How to Use <SCRIPT> Tags

Use of JavaScript in documents:

Regular text and HTML tags... <SCRIPT language> JavaScript commands... </SCRIPT> More text and HTML tags... An example of JavaScript in a document:

<H2>JavaScript Workshop</H2> Welcome to the workshop.<P> <SCRIPT LANGUAGE="JavaScript"> document.write("Here is JavaScript code writing part of the document."); document.write("<P>This shows <B>bold text</B>. "); </SCRIPT> <P>Thanks for joining us!<P>

Here's how that would look:


JavaScript Workshop

Welcome to the workshop.

Thanks for joining us!


JavaScript Within Anchor <A> </A> Tags

JavaScript commands can be associated with events or executed by clicking on anchor tags:

<A [link] [event/commands] [event/commands] > </A> <A HREF="javascript: [commands] > </A> Examples of JavaScript in anchor tags:

<A HREF="www.ship.edu" onMouseOver="window.status='A Great Link!'; return true"> Shippensburg University</A><BR> <A HREF="javascript:window.alert('Glad you could make it!');">Welcome</A> to our workshop.<P>

See how these work:

Check out Shippensburg University's web site.

Welcome to our workshop.


Benefits

Older Browsers

Certain older browsers do not support JavaScript. Because HTML is designed to be upwardly compatible, these browsers would ignore the <SCRIPT> </SCRIPT> tags. However, the text between the tags (the JavaScript commands) would be displayed.

Use the HTML comment tags ( <!-- and --> ) to hide the commands from the browser:

<SCRIPT LANGUAGE="JavaScript"> <!-- Comment tags will hide JavaScript command from older browsers. // --> </SCRIPT> Note that the closing comment tag must also include a JavaScript comment tag ( // ) to hide it from JavaScript.

Exercise 1

Create this simple JavaScript document. Use your name for myname, and make any changes you'd like to the body of the document or the text inside the quotation marks.

<HTML> <BODY> <H2>My First JavaScript</H2> <SCRIPT LANGUAGE="JavaScript"> myname = "Jane Doe"; document.write("This JavaScript example was written by " + myname + ".<P>"); document.write("This browser is <B>" + navigator.appName + "</B>.<BR>"); document.write("The version is <B>" + navigator.appVersion + "</B>.<P>"); document.write("End of " + myname + "'s first script.<P>"); </SCRIPT> </BODY> </HTML>

Your page should look like this.

Next Next: Creating Documents with JavaScript