Download presentation
Presentation is loading. Please wait.
Published byKathleen Curtis Modified over 9 years ago
1
Javascript Browser – Client Side Processing Activity page/examples: http://comp.fsksm.utm.my/~rosely/js/ Browser – Client Side Processing Activity page/examples: http://comp.fsksm.utm.my/~rosely/js/
2
Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
3
Introduction - Outline Introduction – –What is Javacript? – –What Javascript can do? – –Examples usage of Javascript – –How to use Javascript?
4
What is Javascript Official name: ECMAScript maintain by ECMA organisations Official name: ECMAScript maintain by ECMA organisations ECMA 262 – official Javascript standard based on Javascript (Netscape) & Jscript (Microsoft) ECMA 262 – official Javascript standard based on Javascript (Netscape) & Jscript (Microsoft) Invented by Brendan Eich at Netscape (with Navigator 2.0) Invented by Brendan Eich at Netscape (with Navigator 2.0) Development is still in progress! Development is still in progress!
5
What is Javascript Java and Javascript is not the SAME – only similar to Java and C++ Java and Javascript is not the SAME – only similar to Java and C++ The fundamentals of Javascript are similar to Java and/or C++ The fundamentals of Javascript are similar to Java and/or C++
6
What is Javascript? was designed to add interactivity to HTML pages was designed to add interactivity to HTML pages Is a scripting language Is a scripting language an interpreted language (means that scripts execute without preliminary compilation) an interpreted language (means that scripts execute without preliminary compilation) Case-sensitive Case-sensitive Must be embedded into HTML Must be embedded into HTML Browser dependent Browser dependent Execute whenever the HTML doc. which contain the script open by browser. Execute whenever the HTML doc. which contain the script open by browser. Everyone can use JavaScript without purchasing a license Everyone can use JavaScript without purchasing a license
7
What Javascript can do? JavaScript gives HTML designers a programming tool JavaScript gives HTML designers a programming tool JavaScript can put dynamic text into an HTML page JavaScript can put dynamic text into an HTML page JavaScript can react to events JavaScript can react to events JavaScript can read and write HTML elements JavaScript can read and write HTML elements JavaScript can be used to validate data JavaScript can be used to validate data JavaScript can be used to detect the visitor's browser JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies JavaScript can be used to create cookies
8
Examples usage of Javascript - activity 01 Limited capability application Limited capability application –Clocks –Mouse Trailers (an animation that follows your mouse when you surf a site) –Countdown timer –Drop Down Menus The objective of Javascript is not for creating full-blown application running in a browser! The objective of Javascript is not for creating full-blown application running in a browser! Limited capability application Limited capability application –Clocks –Mouse Trailers (an animation that follows your mouse when you surf a site) –Countdown timer –Drop Down Menus The objective of Javascript is not for creating full-blown application running in a browser! The objective of Javascript is not for creating full-blown application running in a browser!
9
Examples usage of Javascript Event management Event management Form management & verification Form management & verification Dynamic HTML (DHTML) Dynamic HTML (DHTML) Client-Server application - AJAX Client-Server application - AJAX
10
How to use Javascript? – activity 02 Inside the head tag (head section) Inside the head tag (head section) Within the body tag (body section) Within the body tag (body section) In an external file (external script) In an external file (external script)
11
How to use Javascript? - head section function message() { alert("This alert box was called with the onload event"); }
12
How to use Javascript? - body section document.write("This message is written by JavaScript");
13
How to use Javascript? - external script // JavaScript Document (myjs.js) function popup() { alert("Hello World") }
14
How to use Javascript? All code inside head tag (except in function) will be executed first before the html load All code inside head tag (except in function) will be executed first before the html load Put global variables in the section script Put global variables in the section script Use document.write/ln to send html output Use document.write/ln to send html output Use window.prompt to get user input Use window.prompt to get user input
15
Use in alert box
16
Debugging Errors: Activities 03 Debugging Errors: Activities 03 Click this. Warning icon means there are some errors in your script
17
Debugging Errors:
18
Simple JS application – input/output
19
Javascript Fundamental A light Java/C++ A light Java/C++ All other things are more or less the same: All other things are more or less the same: –Keyword, variables –Operator –Conditional statement –Looping etc. Case sensitive Case sensitive No strong typing in JS for variable No strong typing in JS for variable
20
Javascript Variables Variables name – case sensitive Variables name – case sensitive No typing! No typing! Can change type during execution Can change type during execution –Activity 05 - a Use double qoute for character and string variable Use double qoute for character and string variable Cannot use reserve word for variable name! Cannot use reserve word for variable name! Variables name – case sensitive Variables name – case sensitive No typing! No typing! Can change type during execution Can change type during execution –Activity 05 - a Use double qoute for character and string variable Use double qoute for character and string variable Cannot use reserve word for variable name! Cannot use reserve word for variable name!
21
OUTPUT: 10 rosely 25 OUTPUT: 10 rosely 25
22
JS – Reserve Word
23
Javascript variables operation Arithmetic operations – same as Java/C++ Arithmetic operations – same as Java/C++ + operators is overloaded, can be used for string + operators is overloaded, can be used for string Number + string (or vice versa), result string Number + string (or vice versa), result string –Activity 05 - b – A = 2 + 5 (result 7) – A = 2 + “5” (result 25) – A = A + 2 (result 252)
24
OUTPUT: 2 25 252 OUTPUT: 2 25 252
25
JS Operators
27
Javascript – Conditional expressions – activity 06 If else, switch statement – same as C++/Java If else, switch statement – same as C++/Java Boolean Boolean –Value 0, false = false –Value 1, true = true String comparison, use the quote! String comparison, use the quote! –if (password == “007”) Check the example! Check the example! If else, switch statement – same as C++/Java If else, switch statement – same as C++/Java Boolean Boolean –Value 0, false = false –Value 1, true = true String comparison, use the quote! String comparison, use the quote! –if (password == “007”) Check the example! Check the example!
28
Javascript – Conditional expressions Special conditional operator Special conditional operator –variablename=(condition)?value1:value2 –variablename=(condition)?value1:value2 –If true value1 assigned else value2 assigned to variablename greeting = (visitor == "PRES") ? "Dear President “ : "Dear ";
29
Javascript – Loop for loop, while loop – same as C++/Java for loop, while loop – same as C++/Java Use break statement to exit loop Use break statement to exit loop JavaScript For...In Statement JavaScript For...In Statement –used to loop (iterate) through the elements of an array or through the properties of an object. – var mycars = new Array(); – for (x in mycars) document.write(mycars[x] + " "); document.write(mycars[x] + " "); Activity 07 Activity 07 for loop, while loop – same as C++/Java for loop, while loop – same as C++/Java Use break statement to exit loop Use break statement to exit loop JavaScript For...In Statement JavaScript For...In Statement –used to loop (iterate) through the elements of an array or through the properties of an object. – var mycars = new Array(); – for (x in mycars) document.write(mycars[x] + " "); document.write(mycars[x] + " "); Activity 07 Activity 07
30
Javascript Array – activity 08 (.1,.2,.3) Array is a built-in object in JS Array is a built-in object in JS –http://www.w3schools.com/jsref/jsref_obj_array.asp http://www.w3schools.com/jsref/jsref_obj_array.asp Means have methods and properties Means have methods and properties Important properties: Important properties: –length (total elements) –For traversing array elements Example method: Example method: –sort() : sorting array elements –join() : combine all array elements into a string
31
Javascript Array - creating var a = new Array(12); var b = new Array(); var c = new Array(12,10,11); var d = [12,10,11]; // same as c var e = [1,,,10]; // 4 elements array, only first & last element initialized
32
Javascript array: inserting values var A =new Array(); A[0]= 10; A[1]= 20; A[2]=“Ali”;A[3]=2.34;Result: A[0] 10 A[1] 20 A[2] Ali A[3] 2.34
33
JS Array: creating and accessing
34
JS Array: sort method
35
Javascript Array - Multidimensional – activity 08.4 Technically, JavaScript doesn't support multi- dimensional arrays Technically, JavaScript doesn't support multi- dimensional arrays Because array is an object, you can put object inside of another object, so emulating a multi dimensional array Because array is an object, you can put object inside of another object, so emulating a multi dimensional array So it is possible to have a different dimension (column) for each row! So it is possible to have a different dimension (column) for each row!
36
Javascript Array - Multidimensional var myarray=new Array(3) var myarray=new Array(3) Create a multidimensional array Create a multidimensional array
37
Javascript Array - Multidimensional
41
JS Array: Associative - Activity 08.5 Using a similar access technique to hash function Using a similar access technique to hash function In this case, the index of an array is using a word or key instead of number. In this case, the index of an array is using a word or key instead of number. This is where For In is use instead of For Loop This is where For In is use instead of For Loop
42
JS Array: Associative
43
Direct access to individual elements Direct access to individual elements Printing the keys! Printing the keys!
44
JS Array: Associative Direct access to individual elements Direct access to individual elements – Ichigo kurosaki – rob lucci Printing the keys! Printing the keys! – BLEACH – NARUTO – ONE_PIECE Direct access to individual elements Direct access to individual elements – Ichigo kurosaki – rob lucci Printing the keys! Printing the keys! – BLEACH – NARUTO – ONE_PIECE
45
JS Array: Associative Printing all elements in array using For..In and For..Loop Printing all elements in array using For..In and For..Loop
46
JS Array: Associative printing the whole array elements at once using join printing the whole array elements at once using join
47
JS Array: Associative printing the whole array elements at once using join printing the whole array elements at once using join
48
Javascript Function Functions in Javascript behave similar to numerous programming languages (C, C++, PHP, etc). Functions in Javascript behave similar to numerous programming languages (C, C++, PHP, etc). Put in head section or external Put in head section or external Variables inside a function is local Variables inside a function is local Use return to return value and exiting the function (return without value) without finishing Use return to return value and exiting the function (return without value) without finishing
49
Javascript Functions Involves two steps: Define: to define what processes should be taken Define: to define what processes should be taken Call/Invoke: to execute the functions Call/Invoke: to execute the functions Syntax of function definition: function function_name (param1, param2,.., param_n) //parameters are optional //parameters are optional{ //function’s code goes here //function’s code goes here return value_or_object; //optional } Involves two steps: Define: to define what processes should be taken Define: to define what processes should be taken Call/Invoke: to execute the functions Call/Invoke: to execute the functions Syntax of function definition: function function_name (param1, param2,.., param_n) //parameters are optional //parameters are optional{ //function’s code goes here //function’s code goes here return value_or_object; //optional }
50
Javascript function – activity 09
51
Javascript Object – activity 10 Objects in Javascript can be created directly using variable declaration or Objects in Javascript can be created directly using variable declaration or Can be instantiated from an existing classes Can be instantiated from an existing classes
52
JS object: directly instantiated var empty = {}; // An object with no properties var point = { x:0, y:0 }; var circle = { x:point.x, y:point.y+1, radius:2 }; var homer = { "name": "Homer Simpson", "name": "Homer Simpson", "age": 34, "age": 34, "married": true, "married": true, "occupation": "plant operator", "occupation": "plant operator", 'email': "homer@example.com" 'email': "homer@example.com"};
53
JS Object: directly instantiated using var
54
JS: Creating class function class_name (property_1,..., property_n) { this.property_1 = property_1... this.property_n = property_n this.method_1 = method_name_1... this.method_n = method_name_n } function method_name_1() {} function method_name_n() {} function class_name (property_1,..., property_n) { this.property_1 = property_1... this.property_n = property_n this.method_1 = method_name_1... this.method_n = method_name_n } function method_name_1() {} function method_name_n() {}
55
JS: Creating class – cont. Example: function Person(aName,age) { this.name = aName; this.age = age; this.displayInfo = print; } function print() { window.alert(“Name= “ + this.name + “\nAge= “ + this.age); } Example: function Person(aName,age) { this.name = aName; this.age = age; this.displayInfo = print; } function print() { window.alert(“Name= “ + this.name + “\nAge= “ + this.age); }
56
JS: Instantiating obj. from class object_name = new class_name (property_1, property_2, …..); Example: // creating an object of class Person person1 = new Person(“Ali”,20); // executing method // executing displayInfo method person1.displayInfo(); // changing property person1.age=23; Example: // creating an object of class Person person1 = new Person(“Ali”,20); // executing method // executing displayInfo method person1.displayInfo(); // changing property person1.age=23;
57
JS Object: Instantiating obj. from class
58
JS Object: Passing parameter to object method
59
JS Object: Passing parameter to object method - continue
60
JS Object: Member access using hash (associative) – activity 10.4 Access similar to associative array Accessing: document.write(person1[‘name’]); document.write(person1[‘age’]); Assignment person1[‘name’] = “rosely”; Access similar to associative array Accessing: document.write(person1[‘name’]); document.write(person1[‘age’]); Assignment person1[‘name’] = “rosely”;
61
JS: Built-in objects Date Date –http://www.w3schools.com/js/js_obj_math.asp String String –http://www.w3schools.com/js/js_obj_string.asp Math Math –http://www.w3schools.com/js/js_obj_date.asp Date Date –http://www.w3schools.com/js/js_obj_math.asp String String –http://www.w3schools.com/js/js_obj_string.asp Math Math –http://www.w3schools.com/js/js_obj_date.asp
62
JS: Built-in objects - Date The Date object is useful when you want to display a date or use a timestamp in some sort of calculation. The Date object is useful when you want to display a date or use a timestamp in some sort of calculation. You can either make a Date object by supplying the date of your choice, You can either make a Date object by supplying the date of your choice, or you can let Javascript create a Date object based on your visitor's system clock. or you can let Javascript create a Date object based on your visitor's system clock. It is usually best to let Javascript simply use the system clock. It is usually best to let Javascript simply use the system clock.
63
JS: Built-in objects – Date - activity 11 getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM getSeconds() - Number of seconds (0-59) getSeconds() - Number of seconds (0-59) getMinutes() - Number of minutes (0-59) getMinutes() - Number of minutes (0-59) getHours() - Number of hours (0-23) getHours() - Number of hours (0-23) getDay() - Day of the week(0-6). 0 = Sunday,..., 6 = Saturday getDay() - Day of the week(0-6). 0 = Sunday,..., 6 = Saturday getDate() - Day of the month (0-31) getDate() - Day of the month (0-31) getMonth() - Number of month (0-11) getMonth() - Number of month (0-11) getFullYear() - The four digit year (1970-9999) getFullYear() - The four digit year (1970-9999)
64
JS: Built-in objects - Date
65
We check to see if hours or minutes is less than 10, if it is then we need to add a zero to the beginning of minutes. We check to see if hours or minutes is less than 10, if it is then we need to add a zero to the beginning of minutes. This is not necessary, but if it is 1:01 AM then our clock would output "1:1 AM", which doesn't look very nice at all! This is not necessary, but if it is 1:01 AM then our clock would output "1:1 AM", which doesn't look very nice at all!
66
Javascript – Window & Boxes –Popup Window –Alert message –Prompt (getting input) –Confirm message –Redirection
67
Javascript: – Popup Window window.open() – activity 12.1 window.open() – activity 12.1 –Creates a new secondary browser window and loads the referenced resource. –window.open(strUrl, strWindowName [, strWindowFeatures]); –strUrl This is the URL to be loaded in the newly opened window. This is the URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, strUrl can be an HTML document on the web, it can be an image file or any type of file which is supported by the browser. it can be an image file or any type of file which is supported by the browser. window.open() – activity 12.1 window.open() – activity 12.1 –Creates a new secondary browser window and loads the referenced resource. –window.open(strUrl, strWindowName [, strWindowFeatures]); –strUrl This is the URL to be loaded in the newly opened window. This is the URL to be loaded in the newly opened window. strUrl can be an HTML document on the web, strUrl can be an HTML document on the web, it can be an image file or any type of file which is supported by the browser. it can be an image file or any type of file which is supported by the browser.
68
Javascript: – Popup Window strWindowFeatures strWindowFeatures –dependent - Subwindow closes if parent(the window that opened it) window closes (yes/no) –height - The height of the new window, in pixels –width - The width of the new window, in pixels –left - Pixel offset from the left side of the screen –top - Pixel offset from the top of the screen –resizable - Allow the user to resize the window or prevent resizing (yes/no) –status - Display the status bar or not (yes/no) –scrollbar (yes/no)
69
JS: Alert - activity 12.2 Creating message box Creating message box No input, only Ok button to continue No input, only Ok button to continue Useful for debugging Useful for debugging –alert (“hello world”); –var name = “rosely”; –alert (“hello ” + name); –var age = 17; –alert (“your age is: “ + age); Creating message box Creating message box No input, only Ok button to continue No input, only Ok button to continue Useful for debugging Useful for debugging –alert (“hello world”); –var name = “rosely”; –alert (“hello ” + name); –var age = 17; –alert (“your age is: “ + age);
70
JS: Prompt – activity 04 Getting input from user Getting input from user –name = window.prompt ("Please enter your name", “polan"); Getting input from user Getting input from user –name = window.prompt ("Please enter your name", “polan");
71
JS: Confirm - activity 12.3 Confirmation are most often used to confirm an important action that is taking place on a website. Confirmation are most often used to confirm an important action that is taking place on a website. For example they may be about to submit an order or about to visit a link that will take them away from the current website. For example they may be about to submit an order or about to visit a link that will take them away from the current website.
73
JS: Comment - activity 12.4 Same as Java/C++ Same as Java/C++ –// single line comment –/* – this – is – a multi line comment */ Same as Java/C++ Same as Java/C++ –// single line comment –/* – this – is – a multi line comment */
74
JS: Redirect - activity 12.5 To send user to your new website location To send user to your new website location In case of changing website address/doman In case of changing website address/doman
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.