Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript (Introduction) Like C/C++ and Java, JavaScript is case sensitive It’s not Java Embedded inside HTML Browser dependent Interpreted language Loosely.

Similar presentations


Presentation on theme: "JavaScript (Introduction) Like C/C++ and Java, JavaScript is case sensitive It’s not Java Embedded inside HTML Browser dependent Interpreted language Loosely."— Presentation transcript:

1 JavaScript (Introduction) Like C/C++ and Java, JavaScript is case sensitive It’s not Java Embedded inside HTML Browser dependent Interpreted language Loosely typed language 1

2 Basic JavaScript Code your javascript code is here 2

3 Embedding JavaScript code inside HTML document js01 alert("Hello, I'm from JavaScript") 3

4 Load the JavaScript code from external source file External source file name: myscript.js External source file content: alert("Hello, I'm from JavaScript - external") HTML file content: js01 4

5 JavaScript Code Execution Automatically when the page is loaded (previous examples) Write JavaScript code as function and execute via event handler js02 function hello() { alert("Hello, I'm JavaScript function") } 5

6 JavaScript Code Execution Execute JavaScript function using onload event: js02... 6 How to create and run JavaScript function from an external source…?

7 JavaScript Code Execution Execute JavaScript function via user actions: js02... Clik me (hypertext link) 7

8 Event Handler Events: Auto triggered by the system - when the browser loading a new page ( onload event) User action - when the user click a button ( onclick event) 8

9 Event Handler Table of events and objects: Event ObjectonClickonSubmitOnChangeonFocusonBluronLoadonUnloadonMouseOveronSelect buttonX resetX submitX radioX checkboxX LinkX X Form X Text XXX X textarea XXX X select XXX window XX 9

10 Debugging JavaScript Code Firefox: Tools > Web Developer > Web Console (Ctrl + Shift + K) Chrome: Tools > JavaScript Console (Ctrl + Shift + I) 10

11 JavaScript Keywords ifelsewhile forbreak continuetruefalsenullreturn intvarinwiththis functionnew 11

12 Variable var myName = "Pi"; myValue = 3.14159; alert(myName); myName = 3.14159 plus2pi = myName + myValue; alert(plus2pi); 12 Dynamic, no specific data type definition. String and number are interchangeable.

13 Variable var firstName = "Hang"; var lastName = "Jee Fatt"; var fullName = firstName + " " + lastName; alert(fullName); 13 String Operations: Concatenation

14 Variable var fullName = "Hang Jee Fatt"; var length = fullName.length; var abbr = fullName[0] + fullName[5] + fullName[9]; alert(fullName + "\nLength: " + length + "\nAbbreviative: " + abbr); 14 String Operations: String properties and methods

15 Variable 15 Numeric Operations: Mostly are the same as implemented in C/C++, Java, PHP, etc.

16 JavaScript Function function plus2num(num1, num2) { var result = num1 + num2; return result; } 16 How to apply this function in HTML document with a form…?

17 Document Object Model (DOM) programming interface for HTML and XML documents In the beginning, JavaScript and the DOM were tightly intertwined, but eventually they evolved into separate entities JavaScript acting as a tools/language to communicate with the interface DOM designed to be independent of any particular programming language It’s possible to communicate with DOM using other languages such as VBScript, Python, Perl, etc. 17

18 HTML DOM Elements element window document event style range selection 18

19 HTML DOM Model window history frame location Navigator String document image Array Date Math applet anchor form area link button radio text reset select checkbox submit password textarea file hidden 19

20 Accessing HTML Object Elements object_ref.object_property object_ref.object_method 20

21 Accessing HTML Object Elements (Methods/Properties) for (property in object_ref) { alert(property + " = " + object_ref[property]); } 21

22 Accessing HTML Object Elements (Methods/Properties) Input Data To access the value of the “IC” input field, use either one of the statements below: document.my_form.ic.value document.getElementById('ic').value 22

23 Accessing HTML Object Elements (Methods/Properties) Input Data The CSS and inner content of HTML tag. var caption = document.getElementById('caption'); caption.style.fontWeight = "bold"; caption.innerHTML = 'Name'; 23

24 Manipulating HTML Object Elements (document & window) Write content into HTML document: document.open(); document.write(" \n"); document.write("Hello World\n"); document.writeln("How are You?"); document.write("World: I'm fine\n"); document.write(" "); document.close() ; 24

25 Manipulating HTML Object Elements (document & window) Open and write/set content into new browser window: newWin = window.open("URL", "windowName", ["windowAttributes"]) ; 25

26 Manipulating HTML Object Elements (document & window) Open and write/set content into new browser Window (example): newWin = window.open("", "myWindwow", "width=400,height=300"); newWin.document.open() ; newWin.document.write("Hello I’m new window"); newWin.document.close() ; 26

27 Manipulating HTML Object Elements (document & window) Print out client browser info.: document.open() document.writeln(" ") document.writeln(" navigator.appCodeName = " + navigator.appCodeName) document.writeln(" navigator.appName = " + navigator.appName) document.writeln(" navigator.appVersion = " + navigator.appVersion) document.writeln(" navigator.mimeTypes.length = " + navigator.mimeTypes.length) document.writeln(" navigator.mimeTypes[0].type = " + navigator.mimeTypes[0].type) document.writeln(" navigator.mimeTypes[0].description = " + navigator.mimeTypes[0].description) document.writeln(" navigator.mimeTypes[0].suffixes = " + navigator.mimeTypes[0].suffixes) document.writeln(" navigator.userAgent = " + navigator.userAgent) document.writeln(" ") document.close() 27

28 Using Built-In Object Element (Date) var today = new Date(); document.open(); document.write(" " + today + " \n"); document.write(" Today (dd/mm/yyyy) is: " + today.getDate() + "/" + (today.getMonth() + 1) + "/" + (today.getFullYear()) + " \n"); document.close(); 28

29 Using Built-In Object Element (String) String handling functions ( var str = "Hello World" ): MethodDescriptionExample charAt(pos) Return the character at the specified index. str.charAt(0) return a value of "H" indexOf(searchText[, startPos]) Return the index of the first occurrence of searchText. str.indexOf("or") return a value of 7 lastIndexOf(searchText[, startPos]) Return the index of the last occurrence of searchText. str.lastIndexOf("l") return a value of 9 substring(startPos, endPos) Return the substring of the string starting at startPos and ending at endPos str.substring(6, 8) return a value of "Wor" 29 Do refer to www.w3schools.com for more string properties and methods.

30 Using Built-In Object Element (Math) Math object properties & functions: ELN10LOG10ESQRT1_2 LN2LOG2EPISQRT2 abscosmintan acosevalpowtoString asinexprandomvalueOf atanfloorround atan2logsin ceilmaxsqrt 30 Example: var result = Math.sqrt(16);

31 Using Built-In Object Element (Array) Define array variable using Array object: var months = new Array() months[0] = "Jan" months[1] = "Feb"... months[11] = "Dec”; 31

32 Using Built-In Object Element (Array) Define array variable using Array object: var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); 32

33 Using Built-In Object Element (Array) Define array variable using Array object: var dayOfAug = new Array(31); for (var i = 0; i < dayOfAug.length; i++) { dateOfAugust[i] = i + 1 } 33

34 Using Built-In Object Element (Array) Array object can be used to store almost everything that exist as primitive or object in JavaScript. var items = new Array; items.push("string1"); items.push(new String("string2")); items.push(Math.PI); items.push(new Date()); var output = ""; for (idx in items) { output += items[idx] + " "; } 34

35 Using Built-In Object Element (Array) Reference to Array item is not limited by integer index value, but also be possible by unique key string value. var month2num = new Array; month2num["Jan"] = 1; month2num["Feb"] = 2; month2num["Mar"] = 3; var output = ""; for (key in month2num) { output += key + " = " + month2num[key] + " "; } 35

36 HTML DOM (Nodes)  HTML objects are standard HTML tags used inside the HTML document  Each of these objects can have child/sub objects that are referred as nodes in JavaScript  It’s possible to dynamically append, navigate, and remove nodes by using JavaScript 36

37 HTML DOM (Nodes) Append Child Node: var list = document.getElementById("ulist"); var item = document.createElement("li"); item.id="item_1"; item.innerHTML = "Apple"; list.appendChild(item); 37

38 HTML DOM (Nodes) Remove Child Node: Apple Grape Orange var list = document.getElementById("ulist"); var item = document.getElementById("item_2"); list.removeChild(item); 38

39 HTML DOM (Nodes) Navigate Child Node: Apple Orange var list = document.getElementById("ulist"); var item = list.firstChild; var pre = document.getElementById("list_data"); while (item) { pre.innerHTML += item + "=" + item.innerHTML + "\n"; item = item.nextSibling; } 39

40 Creating New Object Object literal (JSON): object_ref = { property_1:value_1,..., property_n:value_n }; JavaScript built-in Object() function: object_ref = new Object(); object_ref.property_1 = "value_1";... object_ref.property_n = "value_n"; 40

41 Creating New Object Object constructor: function object_name (arg_1,..., arg_n) { this.property_1 = arg_1;... this.property_n = arg_n; this.method_1 = method_name_1; function method_name_1() {... }... this.method_n = method_name_n; function method_name_n() {... } 41

42 Querying Object Properties Just like array with unique key string index var mark = { project:45, lab:15, final:20 }; var total = 0; for (property in mark) { total += parseInt(mark[property]); } 42


Download ppt "JavaScript (Introduction) Like C/C++ and Java, JavaScript is case sensitive It’s not Java Embedded inside HTML Browser dependent Interpreted language Loosely."

Similar presentations


Ads by Google