Presentation is loading. Please wait.

Presentation is loading. Please wait.

Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley

Similar presentations


Presentation on theme: "Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley"— Presentation transcript:

1 Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley
Chapter 7 Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley Programming the Web

2 Learning Objectives Adding JavaScript to HTML Pages
Working with JavaScript Variables Working with objects Controlling JavaScript programs Forms with JavaScript

3 Getting to Know JavaScript
JavaScript is Netscape’s cross-platform, object-oriented scripting language. It is supported by all major browsers like Netscape and Internet Explorer. JavaScript is not a scaled-down version of Java. It is not Java, nor is it related to Java.

4 Core JavaScript Client-side and server-side JavaScript have the following elements in common: Keywords Statement syntax and grammar Rules for expressions, variables, and literals Underlying object model (although client-side and server-side JavaScript have different sets of predefined objects) Predefined objects and functions, such as such as Array, Date, and Math

5 A First Look at JavaScript
JavaScript code appears embedded within an HTML document <!-- Welcome.htm --> <html><head></head> <body> <script language="javascript"> document.write("Welcome to JavaScript!") </script> </body> </html> Your first JavaScript script

6 A First Look at JavaScript (2)
One of the most common uses for JavaScript is to display text. The Document object makes this possible in JavaScript. <!-- Welcome.htm --> <html><head></head> <body> <script language="javascript"> document.write("Welcome to JavaScript!") </script> </body> </html>

7 The <SCRIPT> Tag
<!--alert.htm --> <html><head> <title>Client Side Scripting with JavaScript</title> <script language="JavaScript"> alert("Welcome to Web Programming!") </script> </head></html> The LANGUAGE attribute in the opening <SCRIPT> tag specifies that JavaScript is the scripting language used here Everything that appears between the opening and closing <SCRIPT> tags is known as the body of the script

8 Where the Put the JavaScript
HTML documents are divided into two sections: a head and body <HTML> <HEAD> <TITLE>Untitled</TITLE> </HEAD> <BODY> . </BODY> </HTML> Place your JavaScript code in the <HEAD> when you want a script to execute (run) when a user triggers it, (such as by clicking) Place your JavaScript code in the <BODY> when you want the script to execute (run) immediately, when the HTML page loads

9 Putting JavaScript in the <HEAD> Section
Usually, all functions are placed in the <HEAD> section, to ensure the script is loaded before the function is called. <html> <head> <script language="javascript"> some statements go here </script> </head> .

10 Putting JavaScript in the <BODY> Section
A script that’s placed in the <BODY> section executes immediately and is known as an Immediate script. <html> <head> </head> <body> <script language ="JavaScript"> some statements go here </script> </body> . You can place an unlimited number of scripts in your HTML document, in both the <HEAD> and <BODY> sections.

11 Working with Variables
A variable is a reserved space in computer memory that JavaScript can use to store data while a script runs. You can use variables to: Store input from the user gathered via your Web page Save data returned from functions Hold results from calculations

12 Working with Variables (2)
JavaScript has four basic data types for variables: Variable Numeric String Boolean null Sample value 10,072 "122 Green Street" true value undefined

13 Declaring a Variable Before you can use a variable to store some data you must define or declare it. You can create a variable with the var statement: var strname = some value You can also create a variable without the var statement: strname = some value Variables are more useful and your code more readable if you use descriptive names that have some association with its contents or purpose.

14 Storing Values in Variables
You should assign a value to a variable when you create it. This is referred to as initializing a variable. The format is as follows: var strname = "Color" Or: strname = "Color" The equal sign (=) is an assignment operator, not an arithmetic operator. The name of the variable is entered on the left side of the assignment operator and the value of the variable is entered on the right side of the operator.

15 Initializing Variables
You should assign a value to a variable when you create it. This is referred to as initializing a variable. The format is as follows: The variable counter is a script-level variable. It can be utilized throughout the script. <html><body> <script language ="JavaScript"> var counter = 1 Sub cmdButton_onClick() var temp = 5 End Sub </script> </body> </html> The variable temp is a procedural variable. It exists only within the cmdButton_onClick function.

16 Working with Arrays An array in JavaScript is a set of values grouped together under a single variable name: colors = new Array("Red", "Yellow", "Blue") The elements of an array are indexed according to their order, starting with 0. The second element in the above array ( "Yellow") could be referred to as colors[1]. You can also specify the number of elements in a new array. This code creates an array of 5 elements: dish = new Array(5)

17 Sample Array: An Example
<!-- Array1.htm --> <html><body> <script language="javascript"> var famname = new Array(6) famname[0] = "Valda" famname[1] = "Glenn" famname[2] = "Sidney" famname[3] = "Myrna" famname[4] = "Jett" famname[5] = "Moonie" for (i=0; i<6; i++) { document.write(famname[i] + "<br>") } </script> </body></html>

18 Sample Array: An Example (2)
This is another way of writing the script to produce the same output: <!-- Array2.htm --> <html> <body> <script language="javascript"> var famname = new Array("Valda","Glenn","Sidney","Myrna","Jett","Moonie") for (i=0; i<famname.length; i++) { document.write(famname[i] + "<br>") } </script> </body></html>

19 JavaScript Functions JavaScript supports several functions that can be executed by an event or called from any script. A function runs code and can also return a result to the script that called it. You define functions at the beginning of a file (in the head section), and call them later in the document. To create a function you define its name, any values (arguments), and statements: function myfunction(argument1,argument2,etc) { some statements } A function with no arguments must include the parentheses: function myfunction() { some statements }

20 Arguments An argument is a variable used in the function. The variable values are values passed on by the function call. By placing functions in the head section of the document, you make sure that all the code in the function has been loaded before the function is called. Some functions return a value to the calling expression function result(a,b) { c=a+b return c }

21 JavaScript Functions This code defines a function and creates an input button that, when pressed, calls the function. The function in turn then displays an alert box with the message “Welcome.” <!-- Function1.htm --> <html><head> <script language="javascript"> function firstfunction() { alert("Welcome") } </script></head> <body> <form> <input type="button" onclick="firstfunction()" value="Call function"> </form> </body></html>

22 Anatomy of a Simple Function
<!-- Function1.htm --> <html><head> <script language="javascript"> function firstfunction() { alert("Welcome") } </script></head> <body> <form> <input type="button" onclick="firstfunction()" value="Call function"> </form> </body></html> When the input button is pressed, the function displays an alert box with the message “Welcome.”

23 The return Statement Functions that return a result must use the "return" statement. <!-- Total.htm --> <html><head> <script language="javascript"> function total(a,b) { return a + b } </script></head> <body> document.write(total(2,3)) </script> </body></html>

24 Controlling Your JavaScript Routines
JavaScript lets you control the order in which your scripts process data through the use of conditional and looping statements. By using conditional statements you can develop scripts that make decisions by evaluating data and criteria to determine what tasks to perform. Looping statements allow you to repetitively execute a line or lines of a script until a certain condition or criteria are met.

25 Conditional Statements
JavaScript provides three forms of conditional statements: if if…else Switch The programming required to create this kind of logic is implemented via conditional controls known as branching.

26 If and If…Else Statements
Use the if statement when you want to execute some code if a condition is true: if (condition) { code to be executed if condition is true } To execute certain code if a condition is true and some other code if a condition is false, use the if....else statement. if (condition) { code to be executed if condition is true } else code to be executed if condition is false

27 Switch Statement The switch statement tests an expression against a number of case options and executes the statements associated with the first one to match. switch (color) { case label1: code to be executed if color = label1 break case label2: code to be executed if color = label2 default: code to be executed if color is different from both label1 and label2 }

28 Switch Statement: Another Code Example
Here, the user receives different messages depending upon what day of the week it is: <!-- Switch1.htm --> <script language="javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date() theDay=d.getDay() switch (theDay) { case 5: document.write("Finally Friday") break case 6: document.write("Super Saturday") case 0: document.write("Sleepy Sunday") default: document.write("I'm looking forward to this weekend!") } </script>

29 Conditional Operator JavaScript also contains a conditional operator (==) that assigns a value to a variable based on some condition: Variable name=(condition)?value1:value2 For example: greeting=(visitor=="PRES")?"Dear President ":"Dear " If the variable visitor is equal to PRES, then put the string "Dear President " in the variable named greeting. If the variable visitor is not equal to PRES, then put the string "Dear " into the variable named greeting.

30 Using Looping Statements
In JavaScript, looping statements force a program do something again and again a specified number of times, until some condition is met or as long as some condition exists. JavaScript provides three forms of looping statements: while do…while for…run

31 Using Looping Statements (2)
A for statement is best used when you want to perform a loop a specific number of times. The do…while and for…run statements are best used to perform a loop an undetermined number of times or while a certain condition exists.

32 While Statements The while statement will execute a block of code while a condition is true: while (condition) { code to be executed } This while statement simply counts 1 thru 10 by incrementing a counter by 1 each time for as long as the counter is less than 11: var i = 0 while(i<11) { document.write(i + "<br/>") i++ }

33 Do…While Statements The do...while statement executes one or more statements at least once, checking that a certain condition is met each time before repeating. If that condition is not met, then control moves to the statement immediately after the loop. The following example counts up in twos for as long as the number is less than 20: var i = 0 do { document.write(i + ".<br/>") i+=2 } while(i<20)

34 For Statements The for statement creates a loop consisting of three optional expressions. The first expression is used to initialize a counter variable, the second (optional) provides a condition that is evaluated on each pass through the loop, and the third updates or increments the counter variable. This example simply counts up from zero for as long as the counter is less than 10: for(i=0; i<10; i++) document.write(i + ".<br/>");

35 JavaScript Syntax Here are the essential characters and punctuation used in JavaScript scripts: Characters // /* */ { and } ; Definition Indicates the start of a comment Begins a comment that spans more than one line Indicates the end of a comment that covers more than one line. Used to indicate a block of code Defines the end of a statement (optional, but still a good idea)

36 All About Forms Forms let you prompt a user for input using elements such as radio buttons, checkboxes and selection lists. <!-- Dropdown.htm --> <html><head> <script type="text/javascript"> function put() { var option= document.forms[0].dropdown.options[document.forms[0]. dropdown.selectedIndex].text var txt=option document.forms[0].favorite.value=txt } </script></head><body><form><p> Select your favorite browser: <select name="dropdown" onchange="put()"> <option>Internet Explorer <option>Netscape Navigator </select> </p><p>Your favorite browser is: <input type="text" name="favorite" value="Internet Explorer"> </p></form></body></html>

37 Creating Mouseovers With event handlers like onMouseMove, onMouseOut, onMouseOver and onClick, you can load a new image for the hyperlink or display text in the status bar of the browser in place of the hyperlink’s URL: <!-- Mouseover.htm --> <html><head> <script language="JavaScript"> function showImage(imgName, imgSrc) { document.all[imgName].src=imgSrc } </script></head> <body> <h3>Here is a Mouseover example</h3> <a HREF=" onmouseover="showImage('imgSomeImage','McGrawHillEducation.gif')" onmouseout="showImage('imgSomeImage','McGrawHillCommunity.jpg')" </a> <img name="imgSomeImage" src='McGrawHillHome.gif' width="200" height="100"/> </body></html>

38 Opening a New Window The window.open method lets you pop open a second window. This method takes four optional parameters: Location Name It’s a good idea to store this object reference in a local variable for later reference (for example, to close it): Set oNavWin = window.open("nav.html") Options Replace History Item

39 Opening a New Window (2) The following code example shows how you can open a navigation window from an HTML page: <!-- OpenWindow.htm --> <html><head> <script type="text/javascript"> function openwindow() { window.open(" } </script></head><body><form> <input type="button" value="Open Window" onclick="openwindow()"/> </form></body></html>

40 The End


Download ppt "Client-Side Scripting with JavaScript Barry Sosinsky Valda Hilley"

Similar presentations


Ads by Google