Professional Documents
Culture Documents
Agenda
Overview of JavaScript How does JavaScript work? Basic JavaScript syntax Examples of JavaScript
What is JavaScript?
A lightweight programming language that runs in a Web browser (client-side). Embedded in HTML files and can manipulate the HTML itself. Interpreted, not compiled. JavaScript is not Java.
Developed by Netscape, not Sun. Only executed in a browser. Is not a full-featured programming language. However, the syntax is similar.
JavaScript can validate the data that users enter into the form, before it is sent to your Web application.
Event example
<html> <head> <script language=javascript> function funct() { // code } </script> </head> <body> <img src=pic.gif onClick=funct();> </body> </html>
Variables JavaScript has untyped variables. Variables are declared with the var keyword:
var num = 1; var name = Mel; var phone = 123-456-7890;
The DOM Unlike other programming languages, JavaScript understands HTML and can directly access it. JavaScript uses the HTML Document Object Model to manipulate HTML. The DOM is a hierarchy of HTML things. Use the DOM to build an address to refer to HTML elements in a web page. Levels of the DOM are dot-separated in the syntax.
2006 IBM Corporation
(browser window)
(URL) (HTML page)
<a> <body> <img> <form>
<input>, <textarea>, <select>
frames tables
rows cells
<frame> <table>
<tr> <th>, <td>
title
<title>
2006 IBM Corporation
JavaScript Examples
Code
<html> <head> <script language=javascript> function showAlert(text) { alert(text); } </script> </head> <body onload=showAlert(This alert displays when the page is loaded!);> . . . OR <body onload=alert(This alert);>
Write to the browser JavaScript can dynamically generate a new HTML page. Use document.writeln(text);
Cannot add to the current page.
If the HTML code youre generating contains quotation marks, you must escape them with a backslash:
document.writeln(<a href=\file.html\>);
2006 IBM Corporation
Page navigation Use the location API to change the HTML file that is loaded in the window. Just set location to another value:
location = page.html;
10
Code
<script language=javascript> function goPage() { var pg = document.theForm.aPage.value; location = "page" + pg + ".html"; } </script> . . . <form name="theForm"> <select name="aPage" onChange="goPage();"> <option selected>Choose a page</option> <option value="1">Page 1</option> <option value="2">Page 2</option> <option value="3">Page 3</option> <option value="4">Page 4</option></select> <input type=reset> </form> . . .
2006 IBM Corporation
Image swap The image swap is really a sleight-of-hand trick. There are two images, each slightly different than the other one. Use the src API in JavaScript to replace one image with the other.
11
Code
<script language="javascript"> function swap(file) { document.globe.src=file; } </script> . . . <img name="globe" src="globe.jpg" onMouseOver="swap('globe2.jpg');" onMouseOut="swap('globe.jpg');">
Form validation Have JavaScript validate data for the server-side programmore efficient.
Processing done on the client. Data sent to server only once. JavaScript can update the original HTML if errors occur server-side program would have to regenerate the HTML page. Server-side program gets the data in the format it needs.
12
Form validation 1. Add an onSubmit event for the form. 2. Use the return keyword to get an answer back from JavaScript about whether the data is valid or not.
return false: server-side program is not called, and the user must fix the field(s). return true: the valid data is sent to the server-side program.
Form validation
13
14
15
Cookies
By default, cookies are destroyed when the browser window is closed, unless you explicitly set the expires attribute.
To persist a cookie, set the expires attribute to a future date. To delete a cookie, set the expires attribute to a past date.
By default, cookies can only be read by the web page that wrote them unless you specify one or more of these attributes:
path allows more than one page on your site to read a cookie. domain allows multiple servers to read a cookie.
16
HTML code
<body onload=readCookie();> <form name="cookieForm" onsubmit=javascript: return setCookie();" action=/cgi-bin/login" method="post"> User ID: <input type="text" name="username"><br> Password: <input type="password" name="pwd"><br> <input type="checkbox" name="persist"> Remember user ID <br> <input type="submit" value="Submit"> </form> ...
2006 IBM Corporation
17
18
2. Put them in the same directory as your HTML file. 3. Add the code to customize the graph in the body section of your HTML.
Code
<script language="javascript" src="graph.js"></script> </head> <body> <script> var g = new Graph(370, 200); g.scale = 10000; g.xLabel = "Month"; g.yLabel = "Number of Rants"; g.title = "Rants 2005"; g.setXScaleValues("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); g.addRow(90000, 80000, 60000, 20000, 10000, 30000, 28000, 15000, 18000, 68000, 92000, 75000); g.build(); </script>
2006 IBM Corporation
19
Clock
Another dynamic content example.
Make each line as granular as possible (use variables). Use alerts to get values of variables and see which lines are not getting processed. When testing form validation, set the action attribute to a dummy HTML pagenot the server-side form. If you get the page, the script works.
20
W3 Schools JavaScript
http://www.w3schools.com/js/
21
Resources David Flanagan, JavaScript: The Definitive Guide. OReilly, 1998. Tom Negrino, Dori Smith. JavaScript for the World Wide Web: Visual QuickStart Guide. Peachpit Press, 2001. Mozilla Developers Center: JavaScript
http://developer.mozilla.org/en/docs/JavaScript
TamingTheBeast.net
http://www.tamingthebeast.net/scripts/freejavascripts.htm
22
Any questions?
i5/OS OS/400
Rational is a trademark of International Business Machines Corporation and Rational Software Corporation in the United States, other countries, or both. Intel, Intel Inside (logos), MMX and Pentium are trademarks of Intel Corporation in the United States, other countries, or both. Linux is a trademark of Linus Torvalds in the United States, other countries, or both. Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both. UNIX is a registered trademark of The Open Group in the United States and other countries. SET and the SET Logo are trademarks owned by SET Secure Electronic Transaction LLC. Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Other company, product or service names may be trademarks or service marks of others. Information is provided "AS IS" without warranty of any kind. All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer. Information concerning non-IBM products was obtained from a supplier of these products, published announcement material, or other publicly available sources and does not constitute an endorsement of such products by IBM. Sources for non-IBM list prices and performance numbers are taken from publicly available information, including vendor announcements and vendor worldwide homepages. IBM has not tested these products and cannot confirm the accuracy of performance, capability, or any other claims related to non-IBM products. Questions on the capability of non-IBM products should be addressed to the supplier of those products. All statements regarding IBM future direction and intent are subject to change or withdrawal without notice, and represent goals and objectives only. Contact your local IBM office or IBM authorized reseller for the full text of the specific Statement of Direction. Some information addresses anticipated future capabilities. Such information is not intended as a definitive statement of a commitment to specific levels of performance, function or delivery schedules with respect to any future products. Such commitments are only made in IBM product announcements. The information is presented here to communicate IBM's current investment and development activities as a good faith effort to help with our customers' future planning. Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore, no assurance can be given that an individual user will achieve throughput or performance improvements equivalent to the ratios stated here. Photographs shown are of engineering prototypes. Changes may be incorporated in production models.
23