Presentation is loading. Please wait.

Presentation is loading. Please wait.

TP 2543 Web Programming Java Script.

Similar presentations


Presentation on theme: "TP 2543 Web Programming Java Script."— Presentation transcript:

1 TP 2543 Web Programming Java Script

2 Class Objectives… To use java script element in web development.
To know the type of data control structure. To under stand the basic method in data control structure.

3 Introduction to JavaScript
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language ; a lightweight programming language JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Client-side Programs were developed to run programs and scripts on the client side of a Web browser

4 What can a JavaScript do?
JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element

5 What can a JavaScript do?
JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer

6 The Development of JavaScript
Jscript is a version of JavaScript supported by Internet Explorer The European Computer Manufacturers Association (ECMA) develops scripting standards The standard is called ECMAScript but browsers still generally call is JavaScript

7 When not to use JavaScript
When you need to access other resources. Files Programs Databases When you are using sensitive or copyrighted data or algorithms. Your JavaScript code is open to the public.

8 Inserting JavaScript into a Web Page File
Outline the main tasks you want the program to perform first A JavaScript program can either be placed directly in a Web page file or saved in an external text file Insert a client-side script in a Web page when using the script element Comments are useful for hiding scripts from older browsers Specify alternative content using the nonscript element for browsers that don’t support scripts (or have their script support disabled)

9 Where to Put the JavaScript
JavaScripts in the body section will be executed WHILE the page loads. JavaScripts in the head section will be executed when CALLED. External JavaScript, If we want to run the same JavaScript on several pages, without having to write the same script on every page, we can write a JavaScript in an external file. Script can be in both side, head and body.

10 Put a JavaScript into an HTML page
<html> <body> <script type="text/javascript"> ... </script> </body> </html> To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script> tag we use the type attribute to define the scripting language. The <script type="text/javascript"> and </script> tells where the JavaScript starts and ends Javascript is case sensitive

11 Put a JavaScript into an HTML page
<html> <body> <!-- <script type="text/javascript"> ... //-- > </script> </body> </html> Comment tag : Some older web browser do not support scripting. In such browser, the actual text of a script often will display in the web page

12 Comment Comments can be added to explain the JavaScript, or to make the code more readable. Single line comments start with //. Multi line comments start with /* and end with */. <script type="text/javascript"> /* The code below will write one heading and two paragraphs */ document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script> View Example

13 Write Statement To write text to a Web page, use the following JavaScript commands: document.write(“text”); or document.writeln(“text”)’ Where text is the content to be written to the page. The document.write() and document.writeln() methods are identical, except that the document.writeln() method preserves any line breaks in the text string.

14 Write Statement <html> <body> <script type="text/javascript"> document.write(“TP2543 Web Programming"); document.write(“Fakulti Teknologi dan Sains Maklumat"); </script> </body> </html> View Example

15 Writeln Statement <html> <body> <script type="text/javascript"> document.writeln(“TP2543 Web Programming"); document.write(“Fakulti Teknologi dan Sains Maklumat"); </script> </body> </html> View Example

16 Write Statement <html> <body> <script type="text/javascript"> document.write(“<h1>TP2543 Web Programming</h1>"); document.write(“Fakulti Teknologi <br>dan “> document.write(“Sains Maklumat"); </script> </body> </html> View Example

17 Write Statement <html > <head>
<title>Printing a Line with Multiple Statements</title> <script type = "text/javascript"> <!-- document.write( "<h1 style = \"color: magenta\">" ); document.write( "Welcome to JavaScript " + "Programming!</h1>" ); // --> </script> </head><body></body> </html> View Example

18 Window Object The three "commands" involved in creating alert, confirm, and prompt boxes are: window.alert() window.confirm() window.prompt()

19 window.alert() This command pops up a message box displaying whatever you put in it <html > <head><title>Printing Multiple Lines in a Dialog Box</title> <script type = "text/javascript"> <!-- window.alert( "Welcome to JavaScript Programming!" ); // --> </script> </head> <body> <p>Click Refresh(or Reload)to run this script again.</p> </body> </html> View Example

20 window.confirm() <script type="text/javascript">
Confirm is used to confirm a user about certain action, and decide between two choices depending on what the user chooses. <script type="text/javascript"> var x=window.confirm("Are you sure you are ok?") if (x) window.alert("Good!") else window.alert("Too bad") </script> View Example

21 Window prompt Prompt is used to allow a user to enter something, and do something with that info <script type="text/javascript"> var y=window.prompt("please enter your name") window.alert(y) </script> View Example

22 Working with Variables and Data
A variable is a named item in a program that stores information As with algebra, JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like Fak_name. Rules for JavaScript variable names: Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character

23 Working with Variables and Data
JavaScript variable types: Numeric variables String variables Boolean variables Null variables You must declare a variable before using it

24 Working with Variables and Data
Numeric variable- any number, such as 13, 22.5, etc Can also be expressed in scientific notation String variable- any group of text characters, such as “Hello” or “Happy Holidays!” Must be enclosed within either double or single quotations (but not both) Boolean variable- accepts only true and false values Null variable- has no value at all

25 Declaring a JavaScript Variable
You can declare variables with any of the following JavaScript commands: var variable; var variable = value; variable = value; Where variable is the name of the variable and value is the initial value of the variable. The first command creates the variable without assigning it a value; the second and third commands both create the variable and assign it a value.

26 Declaring a JavaScript Variable
<html><head></head> <body> <script type="text/javascript"> var myVar = "I am a String"; document.writeln("My variable is: " + myVar); document.writeln("<BR>"); myVar = 1; document.writeln( "My variable is: " + (myVar + 2) ); </script> </body></html> View an Example

27 JavaScript Syntax - Variables and Literals
Dynamic Typing - Variables can hold any valid type of value: Number  var myInt = 7; Boolean  var myBool = true; Function  [Discussed Later] Object  [Discussed Later] Array  var myArr = new Array(); String  var myString = “abc”; Null  var data = “ ” … and can hold values of different types at different times during execution

28 Arithmetic Operators Operator Description Example Result + Addition
x=y+2 x=7 - Subtraction x=y-2 x=3 * Multiplication x=y*2 x=10 / Division x=y/2 x=2.5 % Modulus (division remainder) x=y%2 x=1 ++ Increment x=++y x=6 -- Decrement x=--y x=4

29 <title>Preincrementing and Postincrementing</title>
<html > <head> <title>Preincrementing and Postincrementing</title> </head> <body> <script type="text/javascript"> var c; c = 5; document.writeln("<h3>Postincrementing</h3>"); document.writeln( c ); document.writeln("<br />" + c++); document.writeln("<br />" + c); c = 5; document.writeln("<h3>Preincrementing</h3>" ); document.writeln("<br />" + ++c ); document.writeln("<br />" + c ); </script> </body> </html> view an example

30 Assignment Operators Operator Example Same As Result = x=y x=5 += x+=y
Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators Operator Example Same As Result = x=y x=5 += x+=y x=x+y x=15 -= x-=y x=x-y *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0

31 Others Assignment The + Operator Used on Strings as concatenation
Adding Strings and Numbers The rule is : If you add a number and a string, the result will be a string! txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2; What a very nice day x=5+5; document.writeln(x); x="5"+"5“; document.writeln(x); x=5+"5“; document.writeln(x); x="5"+5; document.writeln(x);

32 Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Example == is equal to x== is false x==“5” is true === is exactly equal to (value and type) x===5 is true x==="5" is false != is not equal x!= is true > is greater than x> is false < is less than x< is true >= is greater than or equal to x>= is false <= is less than or equal to x<= is true

33 (x < 10 && y > 1) is true
Logical Operators Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators Operator Description Example && and (x < 10 && y > 1) is true || or (x==5 || y==5) is false ! not !(x==y) is true

34 Logical Operators <html> <script language="JavaScript"> <!-- x = 3; if((2==x) && (x=5)) { document.write("The && evaluated TRUE!<br>"); } else{ document.write("The && evaluated FALSE!<br>"); } document.write("x=",x,"<br>"); --> </script> </html> view an example

35 String concat match string comparisons substring fixed prototype
string constructors replace string declaration  search anchor slice big small blink  split bold strike charat sub charcodeat substr  concat substring fixed sup fontcolor tolowercase fontsize tosource fromcharcode tostring indexof touppercase  italics valueof lastindexof words length stringbuffer link

36 Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax Example If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear President " else it will be assigned "Dear". variablename=(condition)?value1:value2  greeting=(visitor==“FSSK")?“Good Day FSSK":"Good Day FTSM ";

37 Conditional Operator <html> <SCRIPT LANGUAGE="JavaScript"> <!-- mailFlag = "YES" var message; message = (mailFlag == "YES") ? "A" : "B"; document.write("The conditional operator returns: ",message); --> </SCRIPT> </html> view an example

38 Conditional Statements
In JavaScript we have the following conditional statements: condition False True Statement if statement - use this statement to execute some code only if a specified condition is true Syntax if (condition) {   code to be executed if condition is true } <script type="text/javascript"> var d=new Date(); var time=d.getHours(); if (time<10) {   document.write("<b>Good morning</b>");   } </script> view an example

39 If Selection Structure
If student’s grade is greater than or equal to 60 Print “passed” Grade >=60 Print “passed” F T If (studentGrade >= 60) document.writeln (“passed”); view an example

40 if .. else Selection Structure
False True Statement1 condition Statement2 if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false if (condition)  {   code to be executed if condition is true } else  {   code to be executed if condition is not true }

41 If/Else Selection Structure
If student’s grade is greater than or equal to 60 Print “Passed” Else Print “Failed” Grade >=60 Print “passed” Print “failed” F T If (studentGrade >=60) document.writeln (“passed”) Else document.writeln (“failed”) view an example

42 if .. else Selection Structure
<script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time < 10)  {   document.write("Good morning!"); } else  {   document.write("Good day!"); } </script> view an example

43 Extras getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM
getSeconds() - Number of seconds (0-59) getMinutes() - Number of minutes (0-59) getHours() - Number of hours (0-23) getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday getDate() - Day of the month (0-31) getMonth() - Number of month (0-11) getFullYear() - The four digit year ( )

44 Conditional Statements
False True Statement1 Statement3 Statement2 condition2 condition1 if...else if....else statement - use this statement to select one of many blocks of code to be executed if (condition1) {   code to be executed if condition1 is true } else if (condition2)  {   code to be executed if condition2 is true } else{   code to be executed if condition1 and condition2 are not true   }

45 Nested if/else structure
if (studentGrade >=90) document.writeln (“A”) else if (studentGrade >=80) document.writeln (“B”) if (studentGrade >=70) document.writeln (“C”) if (studentGrade >=50) document.writeln (“D”) document.writeln “F”) view an example

46 Conditional Statements
switch statement - use this statement to select one of many blocks of code to be executed switch(n) { case 1:   execute code block 1   break; case 2:   execute code block 2   break; default:   code to be executed if n is different from case 1 and 2 }

47 Conditional Statements
<script type="text/javascript"> //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");   break; case 0:   document.write("Sleepy Sunday");   break; default:   document.write("I'm looking forward to this weekend!"); } </script> view an example

48 Conditional Statements
Example

49 JavaScript Loops Loops execute a block of code a specified number of times, or while a specified condition is true. In JavaScript, there are two different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true

50 Flowchart for For repetition structure
Var counter = 1 Counter<=7 ++counter True False document.write("The number is " + i); for (var=startvalue; var<=endvalue; var=var+increment) { code to be executed }

51 Repetition For <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> view an example

52 Repetition For <html > <head>
<title>Counter-Controlled Repetition</title> </head> <body> <script type = "text/javascript"> for ( var counter = 1; counter <= 7; counter++ ) document.writeln( "<p style = \"font-size: “ + counter + "ex\“>XHTML font size " + counter + "ex</p>" ); </script> </body> </html> view an example

53 While Repetition structure
The while loop loops through a block of code while a specified condition is true. while (var<=endvalue)  {   code to be executed   } Var counter = 1 Counter<=7 document.write("The number is " + i); ++counter

54 While Repetition structure
<html> <body> <script type="text/javascript"> var i=0; while (i<=5)   {   document.write("The number is " + i);   document.write("<br />");   i++;   } </script> </body> </html> view an example

55 While Repetition structure
<html> <head> <title>Counter-Controlled Repetition</title> <script type = "text/javascript"> <!-- var counter = 1; // initialization while ( counter <= 7 ) { // repetition condition document.writeln ( “ <p style = \"font-size: " + counter + "ex\“> XHTML font size " + counter +"ex</p>" ); ++counter; // increment } // --> </script> </head><body></body> </html> view an example

56 Do/while Repetition Structure
Action (s) condition T F do { statement; } while (condition) ;

57 <html > <head>
<title>Using the do/while Repetition Structure</title> <script type = "text/javascript"> var counter = 1; do { document.writeln( "<h" + counter + ">This is " + "an h" + counter + " level head" + "</h" + counter + ">" ); ++counter; } while ( counter <= 6 ); </script> </head><body></body> </html> view an example

58 Break and Continue Statements
Break and continue can modify the loops. Can be place in while, for, do/while or switch Normally we use when to skip from one action.

59 Break Statements <html> <head> <title>
Using the break Statement in a for Structure </title> </head> <body> <script type = "text/javascript"> for ( var count = 1; count <= 10; count++ ) { if ( count == 5 ) break; // break loop only if count == 5 document.writeln( "Count is: " + count + "<br />" ); } document.writeln("Broke out of loop at count = " + count ); </script> </body></html> view an example

60 Continue Statements <html><head> <title>
Using the continue Statement in a for Structure </title> </head> <body> <script type = "text/javascript"> for ( var count = 1; count <= 10; count++ ) { if ( count == 5 ) continue; // skip remaining code in loop // only if count == 5 document.writeln( "Count is: " + count + "<br />" ); } document.writeln( "Used continue to skip printing 5" ); </script> </body> </html> view an example

61 For...In Statement The for...in statement loops through the elements of an array or through the properties of an object. The code in the body of the for...in loop is executed once for each element/property. for (variable in object)  {   code to be executed   }

62 For...In Statement <html> <body> <script type="text/javascript"> var x; var mycars = new Array(); mycars[0] = "Saab"; mycars[1] = "Volvo"; mycars[2] = "BMW"; for (x in mycars)   {   document.write(mycars[x] + "<br />");   } </script> </body></html> view an example

63 JavaScript Part 2 Function and Objects

64 Objectives are.. Creating JavaScripts Functions Array Working Objects
Array Object String Object Date Object Math Object Number Object RegExp Object Window Object

65 Introduction to Function
To develop and maintain a large program construct it from small, simple pieces divide and conquer

66 Program Modules in JavaScript
JavaScript programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects available in JavaScript The term method implies that a function belongs to a particular object We refer to functions that belong to a particular JavaScript object as methods; all others are referred to as functions. JavaScript provides several objects that have a rich collection of methods for performing common mathematical calculations, string manipulations, date and time manipulations, and manipulations of collections of data called arrays. Whenever possible, use existing JavaScript objects, methods and functions instead of writing new ones. This reduces script- development time and helps avoid introducing errors.

67 Creating JavaScript Functions
Function allow programmer to modularize a program A function is a series of commands that perform an action or calculates a value A function name identifies a function Parameters are values used by the function, (provide the mean for the communication between function) Local variable – variables declared in function Argument – argument in function call assigned to corresponding parameters in the function argument A group of commands set off by curly braces is called a command block. Command blocks exist for other JavaScript structures in addition to functions.

68 Function Syntax for function: functionName(parameters*) {
var a; //local variable functionBody } functionName(argument*);

69 functionName(argument1,argument2,etc)
Call Function Invoked by a function call Function can be call whether it has argument Or without argument functionName(argument1,argument2,etc) functionName()

70 Function without argument
<html><head> <script type="text/javascript"> function myfunction() { alert("HELLO") } </script> </head> <body><form> <input type="button" onclick="myfunction()" value="Call function"> </form> <p>By pressing the button, a function will be called. The function will alert a message.</p> </body></html> View in browser

71 Function with argument
How to pass a variable to a function, and use the variable value in the function function add(a,b) { return a+b; } alert(add(1,2)); View in browser When we declare function like this, the content of the function is compiled (but not executed until we call the function).  Also, you might not know it, but an object with the same name as the function is created.  In the above example, we have an object named "add”

72 Example declare a function by assigning a variable to an unnamed function. var add=function(a, b){ return a+b; } alert(add(1,2)); View in browser

73 Function to return the value
How to let the function return a value <html><head> <script type="text/javascript"> function myFunction(){ return (“<h1>Hello, have a nice day!</h1>") } </script> </head><body> document.write( myFunction()) <p>The script in the body section calls a function.</p> <p>The function returns a text.</p> </body></html> View in browser

74 Function with argument and return the value
How to let the function find the sum of 2 arguments and return the result

75 Example numberA=2 numberB=3 <html><head>
<script type="text/javascript"> function total(numberA,numberB){ return numberA + numberB } </script> </head><body> document.write("<h1> Total = " + total(2,3)+”</h1>”) <p>The script in the body section calls a function with two arguments, 2 and 3.</p> <p>The function returns the sum of these two arguments.</p> </body></html> numberA=2 numberB=3 View in browser

76 Example <script type = "text/javascript"> <!—
document.writeln( "<h1>Square the numbers from 1 to 10</h1>" ); for ( var x = 1; x <= 10; x++ ) document.writeln( "The square of " + x + " is " + square( x ) + "<br />" ); function square( y ){ return y * y; } // --> </script> View in browser

77 Explore JavaScript and OO JavaScript

78 JavaScript Global Functions
JavaScript provides seven global functions as part of a Global object This object contains all the global variables in the script all the user-defined functions in the script all the built-in global functions listed in the following slide You do not need to use the Global object directly; JavaScript uses it for you

79 JavaScript global functions (Conversion and Comparison)
escape(string) - Encodes a string from ASCII into an ISO Latin-1 (ISO ) character set which is suitable for HTML processing. It is passed the string to be encoded, and returns the encoded string. unescape - Converts an ISO character set to ASCII. If a string is "My phone # is ", after the escape function, it is "My%20phone%20%23%20is% ". After unescape, it is "My phone # is ". <script type="text/javascript"> str="TP 2543 Web Programming"; str_esc=escape(str); document.write(str_esc + "<br />") document.write(unescape(str_esc)) </script> View in browser

80 JavaScript global functions (Conversion and Comparison)
eval()- Converts a string to integer or float value. It can also evaluate expressions included with a string. The String() function converts the value of an object to a string. <script type="text/javascript"> eval("x=10;y=20;document.write(x*y)"); document.write("<br />" + eval("2+2")); document.write("<br />" + eval(x+17)); </script> View in browser <script type="text/javascript"> var test1 = new Boolean(1); var test2 = new Boolean(false); var test3 = new Date(); var test4 = new String(" "); document.write(String(test1)+ "<br />"); document.write(String(test2)+ "<br />"); document.write(String(test3)+ "<br />"); document.write(String(test4)+ "<br />"); </script> View in browser

81 JavaScript global functions (Conversion and Comparison)
The parseInt() function parses a string and returns an integer. The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number. If the radix parameter is omitted, JavaScript assumes the following: If the string begins with "0x", the radix is 16 (hexadecimal) If the string begins with "0", the radix is 8 (octal). This feature is deprecated If the string begins with any other value, the radix is 10 (decimal) document.write(parseInt("10.33") + "<br />"); document.write(parseInt(" ") + "<br />"); document.write(parseInt("10",10)+ "<br />"); document.write(parseInt("010")+ "<br />"); document.write(parseInt("10",8)+ "<br />"); document.write(parseInt("0x10")+ "<br />"); document.write(parseInt("10",16)+ "<br />") View in browser

82 JavaScript global functions (Conversion and Comparison)
isNaN(value) - If the value passed is a not a number, the boolean value of true is returned, if it is a number, it returns false. parseFloat() - Returns floating point numbers the same as the parseInt function, but looks for floating point qualified strings and returns their value as a float. <script type="text/javascript"> document.write(isNaN(123)+ "<br />"); document.write(isNaN(-1.23)+ "<br />"); document.write(isNaN("2005/12/12")+ "<br />"); </script> View in browser document.write(parseFloat("123") + "<br />"); document.write(parseFloat("9.683") + "<br />"); document.write(parseFloat("40 years") + "<br />"); document.write(parseFloat("He was 40") + "<br />"); View in browser

83 Array An array is a special variable, which can hold more than one value, at a time.

84 Introduction Arrays JavaScript arrays
Data structures consisting of related data items Sometimes called collections of data items JavaScript arrays “dynamic” entities that can change size after they are created

85 Arrays An array is a group of memory locations
All have the same name and normally are of the same type (although this attribute is not required in JavaScript) Each individual location is called an element An element may be referred to by giving the name of the array followed by index of the element in square brackets ([])

86 Arrays (Cont.) The first element in every array is the zeroth element.
The ith element of array sen is referred to as sen[i-1]. Array names follow the same conventions as other identifiers A subscripted array name can be used on the left side of an assignment to place a new value into an array element can be used on the right side of an assignment operation to use its value Every array in JavaScript knows its own length, which it stores in its length attribute and can be found with the expression arrayname.length

87 Array with 10 elements. NAMA name[0] Ali name[1] Ahmad name[2] Luqman
Nuha name[4] Najiha name[5] Ridwan name[6] Izzuddeen name[7] Anisah name[8] Farah name[9] Zawiyah

88 Using Arrays An array is an ordered collection of values referenced by a single variable name var variable = new Array (size); Where variable is the name of the array variable and size is the number of elements in the array Array are used to store a list of data

89 Array There are many ways to create a JavaScript array.
For example, you can use an array literal, as follows: A literal is a fixed value that you type directly into your code. // Create an empty array var emptyArray = [ ]; // Create an array of fruit var fruits = [ "apple", "pear", "orange", "banana" ];

90 Array You can also create a new Array object: // Create an empty array
var emptyArray = new Array ( ); // Create an empty array that's 15 elements long var emptyElementsArray = new Array ( 15 ); // Create an array of 1 element var myName = new Array ( "Matt" ); // Create an array of fruit var fruits = new Array ("apple“,"pear“,"orange“,"banana”);

91 Array You're not limited to passing literal values to the Array constructor. For example, you can create an array containing the values of some variables: var favouriteFruit = "banana"; var favouriteColour = "red"; var favouriteNumber = 8; var favourites = new Array ( favouriteFruit, favouriteColour, favouriteNumber );

92 Accessing the contents of an array
Each element in an array is given an index, which is an integer value between 0 and one less than the length of the array. The first element has an index of 0, the second element has an index of 1, and so on. To access an element, use the syntax: For example arrayName[index] alert ( favourites[0] ); alert ( favourites[2] ); View in browser

93 Example <html><body> <script type="text/javascript">
var famname = new Array(7) famname[0] = “Ahmad" famname[1] = “Muhammad" famname[2] = “Luqman" famname[3] = “Ridwan" famname[4] = “Izzudden" famname[5] = “Nuha” famname[5] = “Najiha” famname.sort(); for (i=0; i<7; i++) { document.write(famname[i] + "<br>") } </script> </body></html> View in browser

94 Array Object Methods Method Description concat()
Joins two or more arrays, and returns a copy of the joined arrays join() Joins all elements of an array into a string pop() Removes the last element of an array, and returns that element push() Adds new elements to the end of an array, and returns the new length reverse() Reverses the order of the elements in an array shift() Removes the first element of an array, and returns that element slice() Selects a part of an array, and returns the new array sort() Sorts the elements of an array splice() Adds/Removes elements from an array toString() Converts an array to a string, and returns the result unshift() Adds new elements to the beginning of an array, and returns the new length valueOf() Returns the primitive value of an array

95 Some Example <html><body> <script type="text/javascript"> var parents = [“Ahmad", “Adenan"]; var children = [“Luqman", “Najiha"]; var family = parents.concat(children); document.write(family); </script> </body></html> View in browser

96 Two Dimentional Array var myarray=new Array(3)
Creating a two dimensional array

97 Two Dimentional Array <script type="text/javascript"> <!--// function CreateMultiArray() { MultiArray = new Array(5) MultiArray [0] = new Array(2) MultiArray [0][0] = "Tom" MultiArray [0][1] = "scientist" MultiArray [1] = new Array(2) MultiArray [1][0] = "Beryl" MultiArray [1][1] = "engineer" MultiArray [2] = new Array(2) MultiArray [2][0] = "Ann" MultiArray [2][1] = "surgeon" } // End hiding. --> </script>

98 String Object Characters are the fundamental building blocks of JavaScript programs Every program is composed of a sequence of characters grouped together meaningfully that is interpreted by the computer as a series of instructions used to accomplish a task A string is a series of characters treated as a single unit A string may include letters, digits and various special characters, such as +, -, *, /, and $ JavaScript supports Unicode, which represents a large portion of the world’s languages String literals or string constants (often called anonymous String objects) are written as a sequence of characters in double quotation marks or single quotation marks

99 String Object Methods Method Description charAt()
Returns the character at the specified index charCodeAt() Returns the Unicode of the character at the specified index concat() Joins two or more strings, and returns a copy of the joined strings fromCharCode() Converts Unicode values to characters indexOf() Returns the position of the first found occurrence of a specified value in a string lastIndexOf() Returns the position of the last found occurrence of a specified value in a string match() Searches for a match between a regular expression and a string, and returns the matches replace() Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring search() Searches for a match between a regular expression and a string, and returns the position of the match slice() Extracts a part of a string and returns a new string

100 String Object Methods Method Description split()
Splits a string into an array of substrings substr() Extracts the characters from a string, beginning at a specified start position, and through the specified number of character substring() Extracts the characters from a string, between two specified indices toLowerCase() Converts a string to lowercase letters toUpperCase() Converts a string to uppercase letters valueOf() Returns the primitive value of a String object

101 String Object Example <html><body>
<script type="text/javascript"> var str="TP 2543 Web Programming"; document.write("First character: “+str.charAt(3)+ "<br />"); document.write("Last character: " +str.charAt(str.length-1)); </script> </body></html> View in browser <html><body> <script type="text/javascript"> document.write(String.fromCharCode(72,69,76,76,79)); document.write("<br />"); document.write(String.fromCharCode(65,66,67)); </script> </body></html> View in browser

102 Length Method <html><body>
<script type="text/javascript"> var str=“FTSM is great!" document.write("<p>" + str + "</p>") document.write(“panjang =“ +str.length) </script> </body></html> View in browser

103 IndexOf( ) Method <html><body>
<script type="text/javascript"> var str=“TP2543 is a Web Programming!" var pos=str.indexOf(“2543") if (pos>=0){ document.write(“2543 found at position: ") document.write(pos + "<br />") } else{ document.write("School not found!") </script> <p>This example tests if a string contains a specified word. If the word is found it returns the position of the first character of the word in the original string. Note: The first position in The string is 0!</p> </body></html> View in browser

104 Match() method <html><body>
<script type="text/javascript"> var str = " TP2543 is a Web Programming!" document.write(str.match(“Web")) </script> <p>This example tests if a string contains a specified word. If the word is found it returns the word.</p> </body> </html> View in browser

105 Substr() and substring() Method
<html><body> <script type="text/javascript"> var str=" TP2543 is a Web Programming!" document.write(str.substr(2,10)) document.write("<br /><br />") document.write(str.substring(2,10)) </script> </body></html> View in browser string.substring(from, to) string.substr(start,length) 10 char T P 2 5 4 3 i s a w e b .. 1 6 7 8 9 10 11 12 13 14

106 toLowerCase and toUpperCase Method
<html> <body> <script type="text/javascript"> var str=("Hello Apakhabar!") document.write(str.toLowerCase()) document.write("<br><br>") document.write(str.toUpperCase()) </script> </body> </html> View in browser

107 Working with Dates Create a date object to store date information
Method Description getDate() Returns the day of the month (from 1-31) getDay() Returns the day of the week (from 0-6) getFullYear() Returns the year (four digits) getHours() Returns the hour (from 0-23) getMilliseconds() Returns the milliseconds (from 0-999) getMinutes() Returns the minutes (from 0-59) getMonth() Returns the month (from 0-11) getSeconds() Returns the seconds (from 0-59) getTime() Returns the number of milliseconds since midnight Jan 1, 1970 getTimezoneOffset() Returns the time difference between GMT and local time, in minutes getUTCDate() Returns the day of the month, according to universal time (from 1-31) getUTCDay() Returns the day of the week, according to universal time (from 0-6) getUTCFullYear() Returns the year, according to universal time (four digits)

108 Working with Dates getUTCHours()
Returns the hour, according to universal time (from 0-23) getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999) getUTCMinutes() Returns the minutes, according to universal time (from 0-59) getUTCMonth() Returns the month, according to universal time (from 0-11) getUTCSeconds() Returns the seconds, according to universal time (from 0-59) getYear() Deprecated. Use the getFullYear() method instead parse() Parses a date string and returns the number of milliseconds since midnight of January 1, 1970 setDate() Sets the day of the month (from 1-31) setFullYear() Sets the year (four digits) setHours() Sets the hour (from 0-23) setMilliseconds() Sets the milliseconds (from 0-999) setMinutes() Set the minutes (from 0-59) setMonth() Sets the month (from 0-11) setSeconds() Sets the seconds (from 0-59) setTime() Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970 setUTCDate() Sets the day of the month, according to universal time (from 1-31)

109 Working with Dates setUTCFullYear()
Sets the year, according to universal time (four digits) setUTCHours() Sets the hour, according to universal time (from 0-23) setUTCMilliseconds() Sets the milliseconds, according to universal time (from 0-999) setUTCMinutes() Set the minutes, according to universal time (from 0-59) setUTCMonth() Sets the month, according to universal time (from 0-11) setUTCSeconds() Set the seconds, according to universal time (from 0-59) setYear() Deprecated. Use the setFullYear() method instead toDateString() Converts the date portion of a Date object into a readable string toGMTString() Deprecated. Use the toUTCString() method instead toLocaleDateString() Returns the date portion of a Date object as a string, using locale conventions toLocaleTimeString() Returns the time portion of a Date object as a string, using locale conventions toLocaleString() Converts a Date object to a string, using locale conventions toString() Converts a Date object to a string toTimeString() Converts the time portion of a Date object to a string toUTCString() Converts a Date object to a string, according to universal time UTC() Returns the number of milliseconds in a date string since midnight of January 1, 1970, according to universal time valueOf() Returns the primitive value of a Date object

110 Date Object The Date object is used to work with dates and times.
Date objects are created with the Date() constructor. There are four ways of instantiating a date: new Date() // current date and time new Date(milliseconds) //milliseconds since 1970/01/01 new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds)

111 Current Date and Time <html><body>
<script type="text/javascript"> var d = new Date() document.write(d.getDate()) document.write(".") document.write(d.getMonth() + 1) document.write(d.getFullYear()) document.write(“</br>") document.write(d.getHours()) document.write(d.getMinutes()) document.write(d.getSeconds()) </script> </body></html> View in browser

112 Set Date <html><body>
<script type="text/javascript"> var myDate=new Date(); //set a Date object to a specific date (14th January 2010) myDate.setFullYear(2010,0,14); document.write(“set Full Year : “+ myDate); //set a Date object to be 5 days into the future myDate.setDate(myDate.getDate()+5); document.write(“My Date : “+ myDate); </script> </body></html> View in browser

113 getDay() <html><body>
<script type="text/javascript"> var d=new Date(); document.write("<h3 style=\"color:green\"> Today is " + d "</h3>"); var weekday=new Array(7); weekday[0]="Sunday“;weekday[1]="Monday"; weekday[2]="Tuesday“;weekday[3]="Wednesday"; weekday[4]="Thursday“;weekday[5]="Friday"; weekday[6]="Saturday"; document.write("<hr/><h3 style=\"color:green\"> Today is " weekday[d.getDay()] + "</h3>"); </script> </body></html> View in browser

114 Math Object Math object methods allow you to perform many common mathematical calculations. The Math object includes several mathematical constants and methods. JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E. var pi_value=Math.PI; var sqrt_value=Math.sqrt(16); Math.E Math.LN2 Math.PI Math.LN10 Math.SQRT2 Math.LOG2E Math.SQRT1_2 Math.LOG10E

115 Math Object Methods Method Description abs(x)
Returns the absolute value of x acos(x) Returns the arccosine of x, in radians asin(x) Returns the arcsine of x, in radians atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y,x) Returns the arctangent of the quotient of its arguments ceil(x) Returns x, rounded upwards to the nearest integer cos(x) Returns the cosine of x (x is in radians) exp(x) Returns the value of Ex floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithm (base E) of x max(x,y,z,...,n) Returns the number with the highest value min(x,y,z,...,n) Returns the number with the lowest value pow(x,y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle

116 round( ) method <html><body>
<script type="text/javascript"> document.write(Math.round(7.25)); document.write(Math.ceil(7.25)); document.write(Math.floor(7.25)); </script> </body></html> View in browser

117 max( ) & min( ) method <html><body>
<script type="text/javascript"> document.write(Math.max(2,4,9,8)) document.write(Math.min(2,4,9,8)) </script> </body></html> View in browser

118 Number Object Methods The Number object is an object wrapper for primitive numeric values. Number objects are created with new Number(). Method Description toExponential(x) Converts a number into an exponential notation toFixed(x) Formats a number with x numbers of digits after the decimal point toPrecision(x) Formats a number to x length toString() Converts a Number object to a string valueOf() Returns the primitive value of a Number object

119 Number Object Methods <html><body> <script type="text/javascript"> var num = new Number( ); document.write(num.toExponential()+“ “); document.write(num.toExponential(2)+“ “); document.write(num.toExponential(3)+“ “); document.write(num.toExponential(10)+ </br> </hr>); document.write(num.toFixed(0)+“ “); document.write(num.toFixed(1)+” "); document.write(num.toFixed(3)+” "); document.write(num.toFixed(10)+"<br /></hr>"); document.write(num.toPrecision()+"<br />"); document.write(num.toPrecision(2)+"<br />"); document.write(num.toPrecision(3)+"<br />"); document.write(num.toPrecision(10)); </script> </body></html> View in browser

120 RegExp Object Method A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text. Expression Description [abc] Find any character between the brackets [^abc] Find any character not between the brackets [0-9] Find any digit from 0 to 9 [a-z] Find any character from lowercase a to lowercase z [A-Z] Find any character from uppercase A to uppercase Z [a-Z] Find any character from lowercase a to uppercase Z [adgk] Find any character in the given set [^adgk] Find any character outside the given set [red|blue|green] Find any of the alternatives specified

121 RegExp Object Method <html><body> <script type="text/javascript"> var str="fakulti teknologi dan sains maklumat"; var patt1=/[b-k][^a]/g; document.write(str.match(patt1)); </script> </body></html> View in browser

122 RegExp Object Method <script language="JavaScript"> function checkpostal(){ //regular expression defining a 5 digit number var re5digit=/^\d{5}$/ //if match failed if (document.myform.myinput.value.search(re5digit)==-1) alert("Please enter a valid 5 digit number inside form") } </script> <form name="myform"> <input type="text" name="myinput" size=15> <input type="button" onClick="checkpostal()“ value="check"> </form> ^ indicates the beginning of the string. Using a ^ metacharacter requires that the match start at the beginning. \d indicates a digit character and the {5} following it means that there must be 5 consecutive digit characters. $ indicates the end of the string. Using a $ metacharacter requires that the match end at the end of the string. this pattern states: "Starting at the beginning of the string there must be nothing other than 5 digits. There must also be nothing following those 5 digits." View in browser

123 Window Object The window object represents an open window in a browser. If a document contain frames (<frame> or <iframe> tags), the browser creates one window object for the HTML document, and one additional window object for each frame. Method Description alert() Displays an alert box with a message and an OK button blur() Removes focus from the current window clearInterval() Clears a timer set with setInterval() clearTimeout() Clears a timer set with setTimeout() close() Closes the current window confirm() Displays a dialog box with a message and an OK and a Cancel button createPopup() Creates a pop-up window focus() Sets focus to the current window moveBy() Moves a window relative to its current position moveTo() Moves a window to the specified position

124 Window Object Method Description open() Opens a new browser window
print() Prints the content of the current window prompt() Displays a dialog box that prompts the visitor for input resizeBy() Resizes the window by the specified pixels resizeTo() Resizes the window to the specified width and height scrollBy() Scrolls the content by the specified number of pixels scrollTo() Scrolls the content to the specified coordinates setInterval() Calls a function or evaluates an expression at specified intervals (in milliseconds) setTimeout() Calls a function or evaluates an expression after a specified number of milliseconds

125 Window Object <html><head>
<script language=javascript> function openwindow() { window.open(" } </script> </head> <body><form> <input type=button value="Open Window" onclick="openwindow()"> </form></body> </html> View in browser

126 SetTimeout() <html><head> <script type="text/javascript"> function timedMsg() { var t=setTimeout("alert('I am displayed after 1 seconds!')",1000); } </script> </head> <body><form> <input type="button" value="Display alert box!" onClick="timedMsg()" /> </form> </body></html> View in browser

127 Tips for Writing Good JavaScript Code
Use good layout to make your code more readable. Indent command blocks to make them easier to read and to set them off from other code Use descriptive variable names to indicate the purpose of your variables Be careful how you use uppercase and lowercase letters in your code, because JavaScript commands and names are case-sensitive Initialize all variables at the top of your script and insert comments describing the purpose and nature of your variables Add comments to your code to document the purpose of each script Create customized functions that can be reused in different scripts. Place your customized functions in external files to make them available to your entire Web site

128 Conclusion… There are a lot of style in designing web with java script. Object and method will help the programmer to develop a web with a varieties function


Download ppt "TP 2543 Web Programming Java Script."

Similar presentations


Ads by Google