Complete this module and Complete the JavaScript module at http://www.w3sschools.com



Similar documents
«W3Schools Home Next Chapter» JavaScript is THE scripting language of the Web.

JavaScript: Introduction to Scripting Pearson Education, Inc. All rights reserved.

Technical University of Sofia Faculty of Computer Systems and Control. Web Programming. Lecture 4 JavaScript

Step by step guides. Deploying your first web app to your FREE Azure Subscription with Visual Studio 2015

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Government Girls Polytechnic, Bilaspur

Introduction to Java

Web App Development Session 1 - Getting Started. Presented by Charles Armour and Ryan Knee for Coder Dojo Pensacola

Moving from CS 61A Scheme to CS 61B Java

Overview. In the beginning. Issues with Client Side Scripting What is JavaScript? Syntax and the Document Object Model Moving forward with JavaScript

JavaScript and Dreamweaver Examples

WIRIS quizzes web services Getting started with PHP and Java

Example. Represent this as XML

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

JavaScript Introduction

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

LAB MANUAL CS (22): Web Technology

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

JavaScript Basics & HTML DOM. Sang Shin Java Technology Architect Sun Microsystems, Inc. sang.shin@sun.com

JavaScript: Control Statements I

VHDL Test Bench Tutorial

So we're set? Have your text-editor ready. Be sure you use NotePad, NOT Word or even WordPad. Great, let's get going.

MASTERTAG DEVELOPER GUIDE

PHP Tutorial From beginner to master

Script Handbook for Interactive Scientific Website Building

Advanced Tornado TWENTYONE Advanced Tornado Accessing MySQL from Python LAB

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Xtreeme Search Engine Studio Help Xtreeme

Lab 4.4 Secret Messages: Indexing, Arrays, and Iteration

Introduction to Web Design Curriculum Sample

Basic Website Maintenance Tutorial*

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Finding XSS in Real World

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Real SQL Programming 1

LAB 1: Getting started with WebMatrix. Introduction. Creating a new database. M1G505190: Introduction to Database Development

Programming Languages

Now that we have discussed some PHP background

WHAT ELSE CAN YOUR HOME PHONE DO?

Pseudo code Tutorial and Exercises Teacher s Version

Short notes on webpage programming languages

Chapter 1 Java Program Design and Development

Intro to Web Programming. using PHP, HTTP, CSS, and Javascript Layton Smith CSE 4000

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Informatica e Sistemi in Tempo Reale

HTML Basics(w3schools.com, 2013)

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Chapter 1 Programming Languages for Web Applications

Further web design: HTML forms

arrays C Programming Language - Arrays

Java Basics: Data Types, Variables, and Loops

Computational Mathematics with Python

Exercise 1: Python Language Basics

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Yandex.Widgets Quick start

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Using HTML5 Pack for ADOBE ILLUSTRATOR CS5

Hypercosm. Studio.

Lab 5 Introduction to Java Scripts

Cobol. By: Steven Conner. COBOL, COmmon Business Oriented Language, one of the. oldest programming languages, was designed in the last six

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Intro to Web Development

Object Oriented Software Design

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

c. Write a JavaScript statement to print out as an alert box the value of the third Radio button (whether or not selected) in the second form.

Computational Mathematics with Python

CEFNS Web Hosting a Guide for CS212

Cross Site Scripting (XSS) and PHP Security. Anthony Ferrara NYPHP and OWASP Security Series June 30, 2011

Web Design Basics. Cindy Royal, Ph.D. Associate Professor Texas State University

AQA GCSE in Computer Science Computer Science Microsoft IT Academy Mapping

Windows Script Host Fundamentals

ASSEMBLY PROGRAMMING ON A VIRTUAL COMPUTER

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

Web Development and Core Java Lab Manual V th Semester

Sources: On the Web: Slides will be available on:

CS 106 Introduction to Computer Science I

HTML, CSS, XML, and XSL

Java CPD (I) Frans Coenen Department of Computer Science

Semantic Analysis: Types and Type Checking

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Web Development. How the Web Works 3/3/2015. Clients / Server

Dialog planning in VoiceXML

6.170 Tutorial 3 - Ruby Basics

Ruby On Rails. CSCI 5449 Submitted by: Bhaskar Vaish

Example of a Java program

Note: A WebFOCUS Developer Studio license is required for each developer.

Keil C51 Cross Compiler

Web Programming with PHP 5. The right tool for the right job.

Transcription:

JavaScript Introduction JavaScript An object-oriented scripting language, commonly used in html pages, to provide dynamism or forms of dynamism not supported by html. JavaScript is not Java. We ll use JavaScript as an introduction to certain programming concepts and to the idea of expanding HTML s possibilities. Before tacking this module, you should be comfortable with HTML and CSS. Follow-up courses Web Scripting, Digital Libraries, Multimedia Info Systems, Information Architecture, XML Anyone in information work today is expected to have at least a passing knowledge of scripting and programming concepts, ability to use basic scripts in their websites, and understand the relationship between data, users, and interactivity. In this module we introduce the absolute rudiments of these concepts. As you advance in LIS, you ll encounter XML. XML works extremely closely with JavaScript, Ajax, and Java in the web as a client/server model. Readings Complete this module and Complete the JavaScript module at http://www.w3sschools.com JavaScript is a scripting language, as are PHP, perl, ActionScript, and ColdFusion. Scripting languages, like all programs, are compiled, meaning the programmers source code is converted into something by a tool (software called a compiler) that can be understood by the computer. But scripts are not run trough the compiler and read until they re actually called. For example, if your web page has a Java Script, it isn t read by the browser and performed until the browser finishes loading the web page. If there s a mistake in the program, only then it is found. Compiled programs, on the other hand, are submitted to a two-pass compilation and then object or binary code produced. For example, a word processing program was written, probably, in C++ with some routines written in Assembler, and then compiled. The compiler program checks that the programmer used the language s syntax correctly and then passes through the code to optimize it and produce code that can be read by the computer s chip (CPU). For example, programmers use a particular programming language they think is best suited for the task, say C++ or Java. They write source code in that language (see Topic Web-enabled DB for a Java sample). The compiler checks the code and then outputs object code. In C++, for example, the source code might be stored in a file called myfile.cpp. The compiler reads the.cpp file and outputs an object file. A Java program ends in.java. Then the Java compiler converts the code into a.class file. The upshot is this: scripting languages are usually easier to learn and apply but are slower to run. Compiled languages are usually more complex but do far more than scripts and run more quickly. JavaScript. The most common use of JavaScript is to add some kind of dynamism to web pages (.html). How come? Browsers are programmed to understand HTML and CSS and they have built-into them JavaScript interpreters. Like compilers, interpreters read the code, check its syntax, and then execute the code. We must inform the browser that we want to call the interpreter by using the HTML tag <script>. Here s an example of an elementary web page (.html) that calls a JavaScript to in turn creates a dialog box (an alert box ) to appear on the screen and to welcome us: 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://wwww3.org/tr/ html4/strict.dtd"> <html> <head>

<title>my first demo JavaScript</title> alert('hello, visitor to my web page.'); </head> [Note! Most word processing programs convert the apostrophe ' and quotes into a smart quote (e.g., ). Be aware of this and disable this option through the program s preference pane. The code for the smart apostrophe is not the same as the plain quote and the program will not run.] As you know, web pages reference documents and items, such as image files and other websites, that are not part of the webpage. This means the website calls an external file. The same way HTML lets you call an external CSS, so you can call an external JavaScript program. JavaScript programs are stored in files with.js extension, e.g., mywelcome.js : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://wwww3.org/tr/ html4/strict.dtd"> <html> <head> <title>my first demo JavaScript</title> <script type="text/javascript" src="mywelcome.js"> </head> Work through First work through http://www.w3sschools.com/ tutorial on JavaScript. JavaScript is used in web pages to provide more interactivity and dynamism to the static HTML pages. It is useful as an introduction to scripting and programming and a great way to become confident in taking other technical courses and taking control of the uses of technology, rather than be at the mercy of an IT staff. JavaScript Grammar All programming languages have a syntax - the rules. The first thing is to know the four main components of any program: statements: a basic unit, representing a step, e.g., alert( Hello there! ); Statements end in a semi-colon. commands: commands make things happen; they re functions. Recognize them by the use of parentheses (). Data passed to the function for its purposes are called parameters and are contained within the parentheses: the Hello there in the above example is a String parameter, passed to the alert() command. Types of data: The parameters and variables come in different types. See the Topic DataTypes for more info. For the moment, let s look at two kinds: Numbers and Strings. A number is used for calculating or counting. JavaScript is not strongly-typed meaning you can be pretty sloppy with your definitions of variables, but it is better to know about data types in case something goes wrong. For example, there s an object called document that is built into the web browser. The document object has its own functions, one of them is write (meaning print data on the screen ). We can pass numbers or Strings as parameters and do something with them. In this example, we want the results of adding 5 + 10 to appear ( to be written ) on the screen of the web browser: document.write(5 + 10); The browser s JavaScript interpreter first adds 5 + 10 (and stores it in memory as 15); then the browser prints on the screen the result 2

(15). Strings in JavaScript, unlike other programming languages, are indicated by double quotes or single quotes! For example, var myname = "Jane Smith"; is the same as var myname = 'Jane Smith';. [Note: sometimes you want to use quotes within quotes - don t! Switch between double quotes and single quotes: If you want an alert box to show ( Well, Tom. The password is cats rule. ), you ll have to alternate quotes: alert("well, Tom. The password is 'cats rule'."). [Note that document.write() erases everything on the screen first and then displays only what is in the parentheses.] Boolean: a Boolean variable that can hold only one of two values: true or false. Variables: A variable is an address in the computer s memory, identified by a name (e.g., password) and a value (e.g., 938sk1 ). Variables are assigned a data type (e.g., String, integer, float, double, boolean, among others or the programmer creates his own Object type and uses that; see the Topic DataTypes). Variables are first declared and then instantiated: the declaration tells the program you want to make a variable of a certain type with a particular name; when you instantiate it, you assign a value to the variable name. In JavaScript, use the reserve word var to let JavaScript know you re creating a variable. Note that variable names must begin with a letter, $, or _. They cannot have spaces and are case sensitive; Strings use " "; numbers do not. 3 var myname = "Jane Smith"; var salary = 25.10; Variables can be declared in two steps: var myname; myname = "Thomas Mann"; or in one step: var myname = "Matt Damon"; You can declare variables and then using operators combine them or perform arithmetic functions: + add e.g., 5 + 10; lastname + " " + firstname; Only numbers can be subtracted, multiplied, divided or have a modulo: - subtract e.g., 10-5; * multiple e.g., 10 * 5; / divide e.g., 10 / 5; % modulo e.g., 25 % 5; Or multiples at the same time: var x, y, z; var checkhasprinted, salaryhasbeenpaid = false; [here 2 variables are declared and both assigned the boolean value of false.] When you declare a function or use one from a library of prepared functions created by others, you must know what kind of data type the function has been programmed to accept. The alert() function is preprogrammed to accept only String data, so this example is correct: alert( Welcome to class. ); You cannot say alert(53);. It is very common in JavaScript to combine Strings and numbers: You ve checked out 5 items. could be a combination of the String and a number variable.

var checkoutstring = "You\'ve checked out "; var no_of_items = 5; var endofstring = " items"; to create document.write( checkoutstring + " " + no_of_items + " " + items ); Notice we had to embed spaces between the words. We combine numbers, too, in a similar way. We can add a literal number (e.g., 5) to a variable that contains a number value (e.g., var no_of_items) to get var total = no_of_items + 5; Sometimes you need to convert a variable that is a string into a number. We do this by using a function called Number(). Say we have a variable var otheritems = 5 and we want to add this to no_of_items. We can convert the string otheritems into a number by passing the String as a parameter to the Number() function: Number( otheritems ). We can do arithmetic on it, too: var newtotal = Number(otherItems) + no_of_items. You can update a variable anytime by changing its contents: var myname = Smith ; can be changed by entering myname = Jones ; var number = 5; can be changed by saying number = 25; A number variable can refer to itself, too: var mynumber = 5; mynumber += 5 means take the variable mynumber (which is 5) and now add 10 to it, to make mynumber = 15; There are six type shortcuts: += Adds the value on the right to the value on the left; e.g., items += 5 This is the same as typing items = items + 5; -+ Subtracts the values *= Multiples them /= Divides them ++ Adds 1 to the variable, e.g., if items = 5, then items++ now equals 6. -- Subtracts 1 from the variable, e.g., if items = 5, then items-- equals 4. Lab Example 1a: Using a text editor (such as WordPad, NotePad, TextEdit, BBEdit, TextWrangler - but not Microsoft Word or another word processing program) create your own web page for testing JavaScripts. Follow this model: <html><head><title>my test page</title> </title></head> <body> This is a test of JavaScript var myfirstname = 'Jane'; // enter your real name var mylastname = 'Smith'; document.write('<hr/>'); document.write(myfirstname + ' ' + mylastname); </body> </html> 4

Save the file as example1.html and open it with your browser. Try different browsers (Internet Explorer, Safari, Opera, Firefox) and see how they respond. Lab Example 1b: Revise your first JavaScript by providing the end-user a change to enter his or her name. <html><head><title>my test page</title> </title></head> <body> This is a test of JavaScript var name = prompt('what is your name?', ''); document.write('<b>welcome, '+ name + '</b>'); </body> </html> First note how we ve included HTML tags (<b>) and string literals (Welcome, ). You can use any legitimate HTML tag as a string - the browser knows that the < (less than) and > (greater than) signs should be interpreted as HTML, not plain text. Now notice we have 2 script areas. The first causes a dialog box to appear (called prompt()) that shows a message and accepts input from the user. The input is stored in the variable name. Later the second script kicks in and uses what the end-user typed (and stored in name ) to echo the data back to the user. Try it! If you ve reviewed DataTypes topic, you re familiar at least passively with the idea of arrays. An array is just a contiguous block of memory. Arrays are great ways to hold data that is very common or unlikely to change. For example, say you want a list of your favorite authors or composers. You could create a String variable for each one (e.g., var mycomposer1 = "Bach, J. S.";) or create a box, as it were, that holds a bunch of composer Strings. Here, we have extra returns just for clarity s sake. var mycomposers = ['Bach, J. S.', 'Mozart, W. A.', 'Beethovan, L. v.', 'Wagner, R.', 'Offspring.']; Now we have 5 strings in a single box (the array). To get the data out of the box, we specify what number we want (called an index). For example to get the Offspring out, let s say we want a temporary variable nowplaying and assign the name of the group. var nowplaying = mycomposers[4]. Arrays are very common for displaying days of the month and the months of the year. Because computers usually start counting a 0, take away one number; The Offspring may be the 5th element, but they re index is 4. If we want to add a new group, say Cake, to the array, we need to know the size of the array and then add one, e.g., mycomposers[5] = 'Cake'; If you don t know how 5

large the array is - ask it! mycomposers[ mycomposers.length ] = 'Cake'; Notice the mycomposers within the brackets. The second part (.length) tells us right away we have an object (the array is an object) and that the name of the object is mycomposers. Moreover, because our mycomposers copies (inherits) JavaScripts own object called array, we inherit all the behaviors of that object, too. All objects have a built in method of determining their length (their size). The. tells us we are accessing a method in an object.1 Lab Example 2: Revise your first JavaScript by providing creating a website for [your pretend employing] library. Create an array of five authors. Then add text such as This week we re reading... and display each element in the array. Practice both your HTML skills and adding other Strings and numbers. <html><head><title>welcome to the Reading Room</title> </title></head> <body> This is a test of JavaScript var name = prompt('what is your name?', ''); document.write('<b>welcome, '+ name + '</b>'); </body> </html> Conditional statements - control-of-flow Everything cannot happen at the same time in a computer program: we control what happens when by when we call an object and by using logical statements that test for certain conditions. For example, when you get cash from the bank s ATM machine, the ATM system must check first whether or not you have funds to cover the request and that the request isn t over the bank s default limit of $300: if you have enough money in your account to cover the request, then give her the cash. if (you_have_enough_money) then (give her the cash) or in a way the computer can understand: if ( checkifenoughmoney() ) { paythemoney(); Let s try this in JavaScript: var requestamount = 200; var totalinaccount = 4200; if ( requestamount <= totalinaccount ) { paythemoney(); In addition, there s the consequence - what if there isn t enough money? Let s say the ATM has an alert box that apologies and says how much money the person is short. 1 If you re interested in knowing more, you should learn about.push(),.unshift(), pop(), splice(). 6

var requestamount = 200; var totalinaccount = 4200; if ( requestamount <= totalinaccount) { paythemoney(); else { alert('sorry, you are ' + totalinaccount - requestamount + ' short.'); If there are several options, we can add more else if.... if ( some_condition ) { do_onething; else if ( some_other_condition_is_true ) { do_anotherthing; else { when_all_else_fails_do_this; There are several comparison operators you should know: = set a variable equal to this String or number, e.g., var mynumber = 7; == Equal to This checks to see if the variable on the left is equal to the value on the right, e.g., requestamount == 300;!= Not equal to - the! is universal for not, e.g., if amountrequested!= 300 > Greater than < Less than >= Greater than or equal to <= Less than or equal to It is very useful to look for ranges and to loop. Let s say you want to determine grades; scores >= 89 and <=95 are an A-. We can compare the variable (the score) with the ranges. How would you complete this statement? var studentgrade = 75; if ( studentgrade >= 89 && studentgrade <= 95) { alert( You got an A- ); && means and means or Often you need to make sure the variables have been processed before continuing. Here is an example that makes sure the user pressed either n or N before charging out a new book: if ( (key= n ) (key= N ) ) { // check out the next book Applying these to your scripts: 7

Imagine writing a script that advises users of your library or archive that starting next Spring they cannot charge more than 5 items at a time. Let s say they ve completed the checkout and are about to logoff. You want to advise em of the new rule. Lab Example 2: <html><head><title>a note about our policy changes...</title> </title></head> <body> This is a test of JavaScript var name = prompt('what is your name?', ''); var items = prompt('how many items did you check out today?', ''); var limitperday = 5; document.write('<b>thanks!</b>. We appreciate your coming to the library.); document.write('starting next Spring, ' + name +' we will restrict temporarily borrowing to '); document.write('no more than '+limitperday+' items.'); </body> </html> Looping... There are two loops that are vital to programming. One is while... and the other is for. A while statement makes something happen until it is no longer true. For statements continue for a certain number of iterations. Let s say you want to know which printers are on-line. Each printer has its own name so let s store them in an array. var printers = ['Lab', Main Office, Reference Room, Cataloguing, Archives ]; And let s say there s a function built-into the printer that tells our program that the printer is ready to be used. The function returns true if the printer is ready; false if not. Lab Example 3: var num = 0; var printers = ['Lab', 'Main Office', 'Reference Room', 'Cataloguing', 'Archives']; while ( num < 5 ) { if ( isthisprinterready( printers[num] ) { document.write('the printer in + printers[num] + ' is ready.'); else { document.write('sorry, the ' + printer[num] + ' is not yet ready.'); Notice that the variable num has a value of 0. When the while () statement starts, the Interpreter compares the value of num (which is 0) to the limit we used (5). If 0 is less than 5 (which it is!) then perform the statements between the { and the. Once inside that area, there s an if statement. In our example, some code elsewhere checks that the printer is ready. The results of that checking are not stored 8

in a variable we name but we can still gain access to its value. The if () always equates to something that is true or false. So, if isthisprinterready() returns a value of true we tell the user that the printer at index # is ready, otherwise that is it not ready. The other most common loop is the for statement. The for statement requires 4 things: an initial condition, something to test, something to do, and a command to update the something to test: for (some condition; as long as that condition is true; update the condition) { do this every time and do it before you update the condition; In this example, we want to make the numbers between 0 and 100 appear on the screen. Learn this: Let s start with a counter variable (let s call it i for integer). var i = 0; is the some condition ; Next we want to test the condition (as long as i <= 100...) Next we do the task. In this case it is to print the numbers on the screen. Finally, we return to the for statement and update the condition: i++ for (var i = 0; i <= 100; i++) { document.write( The current number is +i); We can use Strings, too: var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; for (var i = 0; i < days.length; i++) { document.write( days[i] ); Finally, it is common to integrate both HTML and JavaScript. Here s an example where the books someone has checked out are stored in an array; the call numbers are in an array; and the due dates are in another array. Since every book, call number, and due date appear in the same order, we can do a lot with very little work. var booktitle = ['Hamlet', 'Macbeth', 'Introduction to Programming', 'Du côté du chez Swann']; var callno = ['B93.223.1 1980', 'B93.224.12 2009', 'QA76.9.4 S9 2010', 'BF13.33.2 1899']; var duedate = ['2010-01-01', '2010-01-01', '2010-01-01', '2010-01-01']; // now we ll combine HTML s ordered list tag <ol> and the data from the array: document.write("<ol>"); for (int i = 0; i < booktitle.length; i++) { document.write("<li>" + booktitle[i] + " " + callno[i] + " " + duedate[i]; to create 9

10 Hamlet B93.223.1 1980 2010-01-01 Macbeth B93.224.12.2009 2010-01-01 Introduction to Programming QA76.9.4 S9 2010 2010-01-01 Du côté du chez Swann BF13.3.2 1899 2010-01-01 [Notice that the spacing is not attractive! How would you improve it?] Functions Finally, one thing to recall is how code is reused and is passed arguments, or parameters. This is the structure of a function: function functionname( any parameters ) { // the work of the function This function printtoday() will display the date. Notice that there are no arguments passed to the function. Notice, too, that the first line of the JavaScript code in the function creates a variable (var), names it today, assigned a value (=), uses the reserve word new (which is what actually causes the computer to create the object); and calls another function ( Date() ) that returns an object of its own (in this case, the object is a Date type object that contains today s date. The date is based on the computer s system date). We would like to extract the date from the Date object by converting it into a String that makes sense to humans (today.todatestring()) and then sending that string to the browser (document.write): function printtoday() { var today = new Date(); document.write(today.todatestring()); Most objects have a built-in method called (.tostring() ) that converts that object into something people can read (instead of the computer s cryptic code way of holding data). Because Dates are so common, there s an extra kind of method that converts just Dates into what we expect to see a date look like. This function s default behavior is to present the date like this: Wed Jul 29 2009. There are ways of extracting the date and presenting in other ways, too. We will look at those later. Lab Example 4: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>date Script Demo</title> <!-- Note: if you want to include your own.css put it here and remove the comments <link href="yourcss.css" rel="stylesheet" type="text/css"> --> function printtoday() { var today = new Date(); document.write(today.todatestring());

11 </head> <body> <h1>a Basic Function</h1> <p>today is <strong> printtoday(); </strong></p> </body> </html> In this final example, you ll create an interactive quiz site. You ll have to think about the functions and how they work together. You can do it! Use a text editor that supports UTF-8, such as Apple s TextEdit or Dreamweaver. Both are available on GSLIS lab computers. You want to recreate this file - type it in by hand - and save it as.html. As you type each line be sure to figure out what each line does. Note that the charset= UTF-8 and that a Chinese character is included. It doesn t matter if you cannot read the Chinese or whether it is correct. The point is to demonstrate the quiz and to experiment. If you enter a Chinese (or Russian or Hindi or any other non- Latin alphabet character) you should be aware that it may not work correctly. [How might you resolve that problem?] Experiment. After you re successful running the script, experiment with different questions or modify the function somehow. Lab Example 4: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/tr/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>mini Quiz</title> var score = 0; // initial score is 0 var questions = [ ['What is the capital of France', 'Paris'], ['How many moons does Earth have?', 1], ['What does mean in English?', 'cat'] ]; //go through the list of questions and ask each one for (var i=0; i<questions.length; i++) { askquestion(questions[i]); //function for asking question function askquestion(question) { var answer = prompt(question[0],''); if (answer == question[1]) { alert('correct!'); score++;

else { alert('sorry. The correct answer is ' + question[1] +'.'); </head> <body> <h1>a Simple Quiz</h1> <p> var message = 'You got ' + score; message += ' out of ' + questions.length; message += ' questions correct.'; document.write(message); </p> </body> </html> Assignment Include and experiment with adding the JavaScript for showing today s date appear on your template website. See also Many applications expand their functionality by letting the end-user create his or her own scripts. Here s a link to Adobe s Introduction to Scripting for its products. [see Adobe Intro to Scripting.pdf There s also the JavaScript-Notes readings for you to complete. See the syllabus site. Also see the.js referred to by the class homepage and in the Demo Files area. 12