Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU.

Similar presentations


Presentation on theme: "Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU."— Presentation transcript:

1 Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

2 2 Introduction to Java Script I Client-Side Programming Lecture Content What is JavaScript? What is JavaScript? What a JavaScript can do? What a JavaScript can do? JavaScript in HTML JavaScript in HTML Scripts in the head and body of a section External JavaScript External JavaScript Variable manipulation In JavaScript Variable manipulation In JavaScript Conditional and Iterative statements Conditional and Iterative statements User defined functions in JavaScript User defined functions in JavaScript Objects and array of Objects Objects and array of Objects

3 3 Scripting Language a scripting language is a simple, interpreted programming language – scripts are embedded as plain text, interpreted by application – simpler execution model: don't need compiler or development environment – saves bandwidth: source code is downloaded, not compiled executable – platform-independence: code interpreted by any script- enabled browser – but: slower than compiled code, not as powerful/full- featured

4 4 Scripting Language JavaScript: JavaScript: – the first Web scripting language, developed by Netscape in 1995 – syntactic similarities to Java/C++, but simpler, more flexible in some respects, limited in others – loose typing, dynamic variables, simple objects JScript: JScript: – Microsoft version of JavaScript, introduced in 1996 – same core language, but some browser-specific differences – fortunately, IE, Netscape, and Firefox can (mostly) handle both JavaScript & JScript – JavaScript 1.5 & JScript 5.0 cores conform to ECMAScript standard VBScript: VBScript: – client-side scripting version of Microsoft Visual Basic

5 5 Common Scripting Tasks adding dynamic features to Web pages adding dynamic features to Web pages – validation of form data (the most commonly used application) – image rollovers – time-sensitive or random page elements – handling cookies defining programs with Web interfaces defining programs with Web interfaces – utilize buttons, text boxes, clickable images, prompts, etc

6 6 Common Scripting Tasks limitations of client-side scripting limitations of client-side scripting – since script code is embedded in the page, it is viewable to all – for security reasons, scripts are limited in what they can do e.g., can't access the client's hard drive e.g., can't access the client's hard drive – since designed to run on any machine platform, scripts do not contain platform specific commands – script languages are not full-featured; slow execution e.g., JavaScript objects are crude, not good for large project development e.g., JavaScript objects are crude, not good for large project development

7 7 What is JavaScript JavaScript is a scripting language - a scripting language is a lightweight programming language; JavaScript is a scripting language - a scripting language is a lightweight programming language; JavaScript was designed to add interactivity to HTML pages; JavaScript was designed to add interactivity to HTML pages; A JavaScript is lines of executable computer code which is usually embedded directly in HTML pages; A JavaScript is lines of executable computer code which is usually embedded directly in HTML pages; JavaScript is an interpreted language (means that scripts execute without preliminary compilation); JavaScript is an interpreted language (means that scripts execute without preliminary compilation); JavaScript is supported by all major browsers, like Netscape and Internet Explorer. JavaScript is supported by all major browsers, like Netscape and Internet Explorer.

8 8 Are Java and JavaScript the same? NO! Java and JavaScript two different languages; NO! Java and JavaScript two different languages; Java (developed by Sun Microsystems) is a powerful and very complex programming language - in the same category as C and C++. Java (developed by Sun Microsystems) is a powerful and very complex programming language - in the same category as C and C++.

9 9 What can a JavaScript do? JavaScript gives HTML designers a programming tool: 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 HTML pages; JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write(" " + name + " ") can write a variable text into an HTML page ; JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write(" " + name + " ") can write a variable text into an HTML page ;

10 10 What can a JavaScript do? (cont’d) 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 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; JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element; JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing. JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server, this will save the server from extra processing.

11 11 JavaScript in HTML The HTML tag is used to insert a JavaScript into an HTML page. The HTML tag is used to insert a JavaScript into an HTML page. E.g. E.g.<script>......

12 12 JavaScript in HTML (Example) Start a script using the tag; Start a script using the tag; Use type attribute to define the language Use type attribute to define the language JavaScript starts, the command for writing some output to a page is JavaScript starts, the command for writing some output to a page is document.write("Hello World!"); document.write("Hello World!"); the tag has to be closed. the tag has to be closed.

13 13 JavaScript in HTML (Example) <html><body> document.write("Hello World!") document.write("Hello World!")</script></body></html>

14 14 JavaScript in HTML (Example)

15 15 Ending Statements with a ( ; ) With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon (;). With traditional programming languages, like C++ and Java, each code statement has to end with a semicolon (;). Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line. Many programmers continue this habit when writing JavaScript, but in general, semicolons are optional! However, semicolons are required if you want to put more than one statement on a single line.

16 16 Where to put the JavaScript Scripts in a page will be executed immediately while the page loads into the browser. This is not always what we want. Sometimes we want to execute a script when a page loads, other times when a user triggers an event.

17 17 Scripts in the head of a section Scripts to be executed when they are called, or when an event is triggered, go in the head section. When you place a script in the head section, you will ensure that the script is loaded before anyone uses it.

18 18 Scripts in the head of a section As an example consider: <html><head> some statements some statements </head>

19 19 Scripts in the body of a section Scripts to be executed when the page loads go in the body to generate content. E.g.: <html><head></head><body> some statements some statements </body>

20 20 Scripts in head and body An unlimited number of scripts can be put in both the body and head sections. E.g.: <html> some statements some statements </head><body> some statements some statements

21 21 External JavaScripts We can run the same script on several pages, without writing the script on each and every page. To do this we write a script in an external file, and save it with a.js file extension, as myfile.js : document.write("This script is external") document.write("This script is external") NOTE: External scripts -> no tag

22 22 External JavaScripts (cntd) Now you can call this script, using the " src " attribute, from any of your pages: Note: place the script at the right position.

23 23 Variables A variable is a "container" for information you want to store. A variable is a "container" for information you want to store. A variable's value can change during the script. A variable's value can change during the script. You can refer to a variable by name to see its value or to change its value. You can refer to a variable by name to see its value or to change its value. Rules for Variable names: Rules for Variable names: – Variable names are case sensitive – They must begin with a letter or the underscore character.

24 24 Declare a Variable You can create a variable with the var statement: You can create a variable with the var statement: var strname = some value var strname = some value You can also create a variable without the var statement: You can also create a variable without the var statement: strname = some value strname = some value

25 25 Assign Values to Variables You assign a value to a variable like this: You assign a value to a variable like this: var strCustomerName = “Smith“ var strCustomerName = “Smith“ or like this: or like this: strCustomerName = “Smith“ strCustomerName = “Smith“ The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "strCustomerName" has the value “Smith". The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "strCustomerName" has the value “Smith".

26 26 JavaScript Data Types & Variables JavaScript has only three primitive data types String : "foo" 'howdy do' "I said 'hi'." "" Number: 12 3.14159 1.5E6 Boolean : true false *Find info on Null, Undefined <html> <head> Data Types and Variables Data Types and Variables </head><body> var x, y; var x, y; x= 1024; x= 1024; y=x; x = “Hello World"; y=x; x = “Hello World"; document.write(" x = " + y + " "); document.write(" x = " + y + " "); document.write(" x = " + x + " "); document.write(" x = " + x + " "); </body></html> variable names are sequences of letters, digits, and underscores that start with a letter or an underscore variables names are case-sensitive you don't have to declare variables, will be created the first time used, but it’s better if you use var statements var message, pi=3.14159; var message, pi=3.14159; variables are loosely typed, can be assigned different types of values

27 27 Conditional Statements Often in a program we want to perform different actions for different decisions. JavaScript has three conditional statements: Often in a program we want to perform different actions for different decisions. JavaScript has three conditional statements: -if statement - use this statement if you want to execute a set of code when a condition is true; -if...else statement - use this statement if you want to select one of two sets of lines to execute; -switch statement - use this statement if you want to select one of many sets of lines to execute

28 28 If condition Use if to test for a condition once. Use if to test for a condition once. The syntax is: The syntax is: if (boolean condition) { Javascript code to be executed Javascript code to be executed }

29 29 If condition (cntd) var d = new Date() var time = d.getHours() if (time < 10) { document.write("Good morning!") } </script>

30 30 If … else condition To execute some code if a condition is true and another code if a condition is false, use the if...else statement. The syntax is To execute some code if a condition is true and another code if a condition is false, use the if...else statement. The syntax is if (condition) {Javascript code} else {Javascript code for the else case} Javascript allows nested if blocks. Javascript allows nested if blocks.

31 31 If … else condition (cntd) var d = new Date() var time = d.getHours() if (time < 10) { document.write("Good morning!") } else { document.write("Good day!") } </script>

32 32 Looping statement Often, we want the same block of code to run a number of times. JavaScript supports three looping statements: -while - loops through a block of code while a condition is true; -do...while - loops through a block of code once, and then repeats the loop while a condition is true; -for - run statements a specified number of times.

33 33 Loops in JavaScript while: while (condition) {code to be executed} {code to be executed}do-while:do while (condition) while (condition)for: for (initialisation; condition; increment) for (initialisation; condition; increment) {code to be executed} {code to be executed}

34 34 While loop example Consider the code: var num=0; while (num < 12) { document.write(num +” ”); num = num + 1; }

35 35 JavaScript Operators & Control Statements <html> <head> Folding Puzzle Folding Puzzle </head><body> distanceToSun = 93.3e6*5280*12; distanceToSun = 93.3e6*5280*12; thickness =.002; thickness =.002; foldCount = 0; foldCount = 0; while (thickness < distanceToSun) { while (thickness < distanceToSun) { thickness *= 2; thickness *= 2; foldCount++; foldCount++; } document.write("Number of folds = " + foldCount); document.write("Number of folds = " + foldCount); </body></html> standard C++/Java operators & control statements are provided in JavaScript +, -, *, /, %, ++, --, …+, -, *, /, %, ++, --, … ==, !=,, ===, !=,, = &&, ||, !,===,!==&&, ||, !,===,!== if-then, if-then-else, switch if-then, if-then-else, switch while, for, do-while, … while, for, do-while, … PUZZLE: Suppose you took a piece of paper and folded it in half, then in half again, and so on. How many folds before the thickness of the paper reaches from the earth to the sun? *Find more info on this subject

36 36 Functions Javascript has a large number of built-in functions to perform a number of operations like abs(x) to find the absolute value of x, sqr(x) for the square of a number and so on). Javascript has a large number of built-in functions to perform a number of operations like abs(x) to find the absolute value of x, sqr(x) for the square of a number and so on). On the other hand, the user is able to define his own functions to perform any custom operations. On the other hand, the user is able to define his own functions to perform any custom operations.

37 37 Functions (cntd) We can define a function by using the function statement. The general form is : The general form is : function functionname(arg1,arg2,…,argn) { function functionname(arg1,arg2,…,argn) { //Javascript code goes } The return statement is used to return the value we want to the program. The return statement is used to return the value we want to the program.

38 38 Functions (cntd) Consider the code: function squarenumber(x){ //finds the square of a number return x*x; } To use it, type var a = squarenumber(12);

39 39 An alternative would be to use the Function() constructor: var v = new Function(arg1,arg2,…,argn); var v = new Function(arg1,arg2,…,argn); For example: var z= new Function(“x”,”y”,”return x*y;”); var z= new Function(“x”,”y”,”return x*y;”); multiplies two numbers. Argument 1 Argument 2 Function Body Functions (cntd)

40 40 Finally, we can use function literals. This is done via the statement This is done via the statement var f=function(arg1,…,argn) {statements}; var f=function(arg1,…,argn) {statements}; e.g. the square of a number: e.g. the square of a number: var f=function(x) {return x*x;} var f=function(x) {return x*x;} Functions (cntd)

41 41 Lifetime of variables Local variables i.e. variables declared within a function can only be accessed within that function. Exiting the function, the variable is destroyed. Local variables i.e. variables declared within a function can only be accessed within that function. Exiting the function, the variable is destroyed. Local variables with the same name can be declared in different functions, as each is recognized only by the function in which it is declared. Local variables with the same name can be declared in different functions, as each is recognized only by the function in which it is declared. A variable declared outside a function can be accessed by all the functions on your page. The lifetime of these variables starts when they are declared, and ends when the page is closed. A variable declared outside a function can be accessed by all the functions on your page. The lifetime of these variables starts when they are declared, and ends when the page is closed.

42 42 Objects Objects are composite data types, used to hold a number of properties. E.g. a car has color, brand etc. E.g. a car has color, brand etc. To set or retrieve properties of an object, we use either the dot notation E.g. car.color=“red”; range = car.range ; E.g. car.color=“red”; range = car.range ; Or associative arrays: e.g. car[“color”]=“red”;).

43 43 Creating Objects To create an object, use the new constructor (this assumes that a function that defines the object exists). To create an object, use the new constructor (this assumes that a function that defines the object exists). As an example, consider the code As an example, consider the code var a = new Square(12). var a = new Square(12). We also need a constructor function to initialize the object. We also need a constructor function to initialize the object. Example: Example: function Square(x){ this.side=x; }

44 44 Creating Objects Alternatively, we can create an object simply by assigning values to its properties (this serves as its definition as well, if it has not been been defined previously). For example: var john={ var john={ name:”John Smith”, age:35,phone:12345678};

45 45 Insert & Delete of Object Property We can create a new property for the object simply by assigning a value to it. As an example, consider: john.salary = 12500;. If you want to delete a property, use delete. (e.g. delete john.phone; ). You need to be very careful in delete process as this will delete the property for good.

46 46 Array Objects The Array object is used to store a set of values in a single variable name. Each value is an element of the array has an associated index number. You create an instance of the Array object with the "new" keyword. The following example creates two arrays, both of three elements: var family_names = new Array(3) var family_names = new Array(3) var family_names=new Array(“John","Jani","Stale") var family_names=new Array(“John","Jani","Stale")

47 47 Array Objects (cntd) You can refer to a particular element in the array by using the name of the array and the index number. The index number starts at 0. You can refer to a particular element in the array by using the name of the array and the index number. The index number starts at 0. If you create an array with a single numeric parameter, you can assign data to each of the elements in the array like this: family_names[0]=“John“ family_names[0]=“John“ family_names[1]="Jani“ family_names[1]="Jani“ family_names[2]="Stale" family_names[2]="Stale"

48 48 Array Objects (cntd) And the data can be retrieved by using the index number of the particular array element you want, like this: father=family_names[0] father=family_names[0] mother=family_names[1] mother=family_names[1]

49 49 Object Hierarchy

50 50 Further Reading Javascript: The definitive guide, by D. Flanagan. Javascript: The definitive guide, by D. Flanagan. Mastering Javascript and Jscript by J. Jaworski. Mastering Javascript and Jscript by J. Jaworski. Javascript for the World Wide Web by T. Negrino & D. Smith. Javascript for the World Wide Web by T. Negrino & D. Smith. http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/ http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/ www.w3schools.com/js/js_howto.asp www.w3schools.com/js/js_howto.asp

51


Download ppt "Lecture 7 Introduction to Java Script Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU."

Similar presentations


Ads by Google