Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript.

Similar presentations


Presentation on theme: "JavaScript."— Presentation transcript:

1 JavaScript

2 Basics Single and double quotes in JavaScript
You can write the above code with single quotes too and it will give the same result. However, if the text contains double quotes that have to be displayed, you should use single quotes to surround the text as in: document.write('JavaScript is "NOT" Java'); 

3 Basics <SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT"> <!-- document.write("JavaScript is <B>great</B>."); //--> </SCRIPT> You'll notice that along with the text I've thrown in the HTML bold tag. HTML tags enclosed in write() are not displayed. The browser interprets these tags accordingly and then prints the result. In our case, the word 'great' is displayed in bold.

4 Basics <SCRIPT LANGUAGE="JAVASCRIPT" TYPE="TEXT/JAVASCRIPT"> <!-- document.write('<FONT COLOR="#0000FF">Blue denim</FONT>'); //--> </SCRIPT> Note that I have used single quotes to include the text in write(). Why? Because it is my habit to contain HTML attribute values with double quotes. If I had used double quotes to surround both the attribute value and the text in write(), I would have received an error from the JavaScript interpreter.

5 Nature of Javascript JavaScript is not a true Object Oriented language as C++ or Java but rather an Object Based language. Object Properties To describe a bear or a panda, we specify its characteristics such as color, size, weight, eating habits, the place where its found etc. These are properties of the animal. Polar Bears Color: White Diet: Fish, seals... non-vegetarian Location: The North Tundra It eats, runs, swims, hibernates in the winter season etc. Such actions are the functions of the animal object. Functions in object programming are called methods.

6 Object JavaScript Objects
Objects in JavaScript are software entities such as the browser window or an HTMLdocument. Let's describe the browser window object and some its properties and methods. A browser window object is created whenever a document is loaded in a browser. Its Properties Width Height Name The URL of the document it displays Its Methods Open Close Resize

7 Object hierarchy Consider an analogy of our galaxy (Milky Way) object that consists of other objects such as our solar system which further contains objects such as the Earth and the Sun. An easy way to describe the Earth to an alien residing in some other galaxy would be: Milky way - Solar System - Earth Note that the above can also be written as: Universe - Milky Way - Solar System - Earth

8 Object hierarchy JavaScript uses the period to separate the parent object from its components. Hence, to refer to the document object we use the following notation: window.document A HTML Form called contactform inside the document might be referred as:window.document.contactform For convenience, webdevelopers name HTML elements using the NAME attribute. Thus, a text field named address located in a form named contactform is refered as: window.document.contactform.address or a radio button called answer as: window.document.contactform.answer or text field called name as: window.document.contactform.name

9 Example To refer to the source of an image named logo we use: document.logo.src Similarly, its width is refered as: document.logo.width

10 Assign value to Text field
To set the value of a text field, we use the = (equal too) operator as: document.contactform.add.value = "Type your address here"; This is a JavaScript statement that instructs the browser to displays the text Type your address here in the text field add.

11 METHODS Methods define functions performed by an object. Making a reference to an object method is similar to referencing its property. Thus, document.write(); calls the write() method of the document object. Herein lies an important difference in how methods and properties are refered. Methods are always followed by a pair of parenthesis. Different objects have different methods associated with them. The submit() method of a form object causes the form to be submitted. The log() method of the Math object computes the logarithm of the number supplied. document.myform.submit(); causes myform to be submitted. Math.log(2); computes the logarithm of 2. The number is passed to the method inside the parenthesis and is called the argument.

12 Alert Method alert() is a method of the window object. It is employed to display pop-up boxes with some text and a button labeled "OK". Usage of the alert() method is similar to the write() method of the window object. The text placed inside the parenthesis is displayed on the pop-up box. window.alert("I am an alert box"); Since it's not necessary to specify the window object we can leave it out from the code. Thus, the following code will function equally well as the one above.

13 Onmouseover event handler
JavaScript is all about making web pages respond to actions or events. These events can be of two types depending on how they are generated. Actions such as mouse movements or mou What are event handlers? Event handlers are small JavaScript code placed inside an HTML tag. They help in handling (catching) events. Here is the code from session 1: <A HREF=" onmouseover="alert('Go back to Home Page')"> Home Page</A>

14 Onmouseover & onmouseout
More interactivity - making several things happen at the same time <A HREF=" onmouseover="document.bgColor='#FFFF00'" onmouseout="document.bgColor='#FFFFEE'"> Move your mouse over me! </A>

15 Opening New Windows (pop-up) in JavaScript
Like the alert() method, the open() also takes arguments. When used without any arguments, the new window displayed is blank. Here I tell you how to embellish this new window. <A HREF="javascript:void(0)" onclick="window.open('welcome.html')"> Open a new window</A>

16 Opening a new window through a function
<SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT"> <!-- function open_win() { window.open('welcome.html','welcome','width=300,height=200, menubar=yes,status=yes,location=yes, toolbar=yes,scrollbars=yes'); } //--> </SCRIPT> We name this function open_win and place it in the HTML head section. <A HREF="javascript:void(0)" onclick="open_win()"> Get a welcome message</A>

17 Data Types Data types Variables store data. In JavaScript, this data can be of several types: Number: an integer or a floating-point number. String: Consists of alphabet, numerals or any other characters (even escape characters). Boolean: A logical true or false value. Null: Consists of a value, null. Undefined: Consists os a value, undefined.

18 ++ vs +1 So why use a++ instead of a = a + 1? The reason is that the JavaScript engine does the calculation for increment and decrement operators much faster. The difference in speed is not perceptible for small calculations and loops, however, with thousands of calculations, you'll notice that the processing with the increment or decrement operator is much faster.

19 look at how JavaScript handles digits as string data.
var page = "15"; var page2 = page + 1; var page3 = page + "2"; (note the quotes) Result: page2 = "151"; page3 = "152"; The reason is that the variable page stores digits as string data, the + sign, in this case behaves as the string concatenation operator and not as the arithmetic addition operator.

20 Example var res = * 4; JavaScript has this inbuilt thing called Operator Precedence. It's a list of operators specifying the order in which they will be executed if two or more are found in the same expression. In our case, the multiplication operator has a higher precedence than the addition operator. Hence, JavaScript will first multiply 100 with 4 and add 25 resulting in 425.

21 If statement he beauty of programs lies in the fact that they are able to take decisions on the basis of information you provide. In all the programming languages I've come across, the Ifstatement is extensively used for this purpose. It's actually quite simple to use the if statement and here is the format of an if statement. var a = 5; var b = 5; if (a == b) { alert("The two quantities are equal"); }

22 Relational Operator The == comparison operator does the job of checking the two variables. The other Comparison operators are: !=   Not equal to <   Less than >   Greater than <=   Less than or equal to >=   Greater than or equal to

23 Comparison operator The == is a 'Comparison Operator' while = is an 'Assignment Operator'. Be sure to use the comparison operator in a condition. If you use the assignment operator, the code will not function and JavaScript will NOT throw an error... it'll simply reassign the variable on the left.

24 Confirm Box A 'Confirm' box was displayed when you first entered this page. It's brought about by using the confirm() method of the window object, similar to the alert box. var response = confirm("Have you understood the confirm box?"); if (response == false) { alert("Go thru the sessions again"); }

25 NOT Operator The exclamation mark ! is called the NOT operator. It reverses the return value of a condition. Thus, !(true) is returned as false and !(false) returns true. var a = 10; if (!(a == 10)) { alert("The magic of JavaScript"); } else { alert("The beauty of JavaScript"); }

26 Navigator Object etting client (browser) details is very easy through JavaScript. Client name, version, codename and the platform used are available through the navigator object and its properties. (The navigator object was named after Netscape Navigator). navigator.appName - Gives the name of the browser (application Name) navigator.appVersion - Gives the browser version (application Version) navigator.appCodeName - Gives the browser codename (application CodeName) navigator.platform - Gives the platform on which the browser is running

27 Browser detection some web develpers make two versions of their site, one that is compatible with Internet Explorer and the other that contains Netscape Navigator specific code. These developers use a browser detection script to transfer the visitor to the respective site. We'll concentrate only on Internet Explorer and Netscape Navigator since they are the most prominent browsers on the Internet.

28 Window property - location
To automatically transfer the visitor, we have to take the help of location property of the window object. Let's look at the code. <SCRIPT LANGUAGE="JavaScript" TYPE="TEXT/JAVASCRIPT"> <!-- var bname = navigator.appName; if (bname == "Microsoft Internet Explorer") { window.location="explorer_version.html"; } else window.location="netscape_version.html"; } //--> </SCRIPT>

29 Date and Time Date and Time in JavaScript
The date object is very useful for obtaining the date and time on the client. It supports various methods, which return a specific value. To start working with dates and time, we first initialize a variable and assign it a value with the new operator and the Date() constructor. The main function of the new operator with Date() constructor is to create a new date object that is stored in the variable. Here is the code: var d = new Date();

30 Methods of Date object Thus, variable d contains a new date object. We can now call the various methods of thisdate object. var t_date = d.getDate(); // Returns the day of the month var t_mon = d.getMonth(); // Returns the month as a digit var t_year = d.getFullYear(); // Returns 4 digit year var t_hour = d.getHours(); // Returns hours var t_min = d.getMinutes(); // Returns minutes var t_sec = d.getSeconds(); // Returns seocnds var t_mil = d.getMilliseconds; // Returns Milliseconds Now we can easily display the date, month and year in an alert box, using the values stored in respective variables. alert("Today's date is " + t_date + "-" + t_mon + "-" + t_year);

31 Else If var d = new Date(); var t_hour = d.getHours();
if (t_hour <= 3) { alert("Hello dear visitor,\nWorking late aren't we?"); } else if (t_hour > 3 && t_hour < 12) alert("Good morning dear visitor"); else if (t_hour >=12 && t_hour <= 16) alert("Good afternoon dear visitor"); Else alert("Good Evening dear visitor");

32 Getting User Input The prompt() is a method of the window object, just like alert() or confirm(). The format for prompt() is similar to alert() or confirm() except for one addition. prompt("Message", "default value in the text field"); In addition to the "OK" and "Cancel" buttons, a prompt box also has a text field that is employed for gathering visitor input. JavaScript lets you specify a default text for this text field. This is optional, that is you can construct  prompt() without specifying the default text. In such cases, JavaScriptdisplays an ugly "undefined" value in the text field.

33 Prompt() var name = prompt("What is your name", "Type you name here");
alert("Hi " + name + "\nHope you are enjoying JavaScript!"); Javascript provides two functions to convert this string value to a numeric data type; parseInt() and parseFloat(). The parseInt() converts a string to an integer value while parseFloat() parses the string converting it to a floating point number. Note: An integer is a whole number without any fractional part while floating- point numbers have a decimal part.

34 Parseint() Now let's write a small script that takes a number from the visitor, checks whether its odd or even and displays the result through an alert box. var n = prompt("Check your number", "Type your number here"); n = parseInt(n); if (n == 0) { alert("The number is zero"); } else if (n%2) alert("The number is odd"); Else alert("The number is even");

35 Example When parseInt() or parseFloat() encounter alphabet or any non-digit character, parsing (conversion) stops and the functions return NaN, which means Not a Number. The only way to test for NaN is to use isNaN() function. var n = prompt("Check your number", "Type your number here"); n = parseInt(n); if (isNaN(n)) { alert("The input cannot be parsed to a number"); } Else { if (n == 0) { alert("The number is zero"); } else if (n%2) { alert("The number is odd"); } else { alert("The number is even"); } }

36 Local & Global Variables
Since functions are separate from the main code, it's advisable to use variables that are initialized only when a function is called and die when the execution comes out of the function. Variables that exist only inside a function are called Local variables. They have no presence outside the function. The values of such Local variables cannot be changed by the main code or other functions.  Variables that exist throughout the script are called Global variables. Their values can be changed anytime in the code and even by other functions.

37 Variable scope What is "variable scope"?
Local variables exist only inside a particular function hence they have Local Scope. Global variables on the other hand are present throughout the script and their values can be accessed by any function. Thus, they have Global Scope.

38 Example Any variable that is initialized inside a function using the var keyword will have a local scope. If a variable is initialized inside a function without var, it will have a global scope. A local variable can have the same name as a global variable. var a = 10; disp_a(); function disp_a() { var a = 20; alert("Value of 'a' inside the function " + a); } alert("Value of 'a' outside the function " + a);

39 Return statement in function
The JavaScript "return" statement in a function The statements in a function are executed line by line, from top to bottom. This flow of execution can be stopped by including a return statement, which causes the function to return a value, hence the statements after return are not executed. Its syntax is: return expression as in: function cal_avg() { var avg = sum_total / n; return avg; }

40 Basics of loop When the JavaScript interpreter comes across a for loop, it executes the initialization statements and then checks the condition. Only when the condition returns 'true', the interpreter enters the loop. After the first iteration, the updation statements are executed and then the condition is evaluated again. This continues till the condition returns 'false' and the loop stops. Some important points to note are: The initialization statements are executed once; only when the for loop is encountered. After execution of initialization statements, the condition is evaluated. After every iteration, the updation statements are executed and then the condition is checked.

41 For loop We can use a for loop to print digits 1 to 10 in an alert box. var msg = ""; for (var x = 1; x <= 10; x++) { msg = msg + x + "\n"; } alert(msg); First, the variable x is initialized to 1, the condition is then evaluated. Since x is less than equal to 10, the statements inside the for loop are executed. The JavaScript interpreter then runs the updation statement that adds 1 to variable x. The condition is again checked. This goes on till the value of x becomes larger than 10. At this point, the statement immediately following the for loop is executed.

42 Example Displaying the 12 times table in an alert box var msg = "";
var res = "0"; for (var x = 1; x <= 12; x++) { res = 12 * x; msg = msg + "12 X " + x + " = " + res + "\n"; } alert(msg);

43 While loop In the previous session, we had used the for loop to display digits 1 to 10 in an alert box. We'll now employ the while loop to do the same thing. var msg = ""; var x = 1; while (x <= 10) { msg = msg + x + "\n"; x++; } alert(msg);

44 Basics of increment operator
Note that the initialization statement (X = 1) has been placed before the loop. The condition lies between the parenthesis and the updation statement (x++) is present inside the statement block. It's a common error by beginners to forget the updation statement in which case the codition will never evaluate to 'false' and this will result in an infinite loop. To avoid such situations, write the updation statement right after starting the statement block.

45 While loop We can also employ the while loop to display the 12 times table as we had done with for. var msg = ""; var x = 1; var res = 0; while (x <= 10) { res = 12 * x; msg = msg + "12 X " + x + " = " + res + "\n"; x++; } alert(msg)

46 Do-while loop You can consider the do-while loop as a modified version of the while loop. Here, the condition is placed at the end of the loop and hence, the loop is executed at least once. var x = 20; do { alert("The number is " + x); x++; } while (x <= 10); In the code above, the value of variable x is 20, hence the condition evaluates to 'false'. However, the loop is executed once since the condition is presented at the end of the loop and not at the beginning.

47 Example We'll now construct an image tag and give the image a name using its NAME attribute. <IMG SRC="icon1.gif" NAME="but" WIDTH="100" HEIGHT="50" BORDER="0" ALT="..."> We use icon1.gif as the value for the SRC attribute since this is the image used for mouseout. The image is named but. The two event handlers are placed inside the starting <A> tag. <A HREF="some.html" onmouseover="document.but.src='icon2.gif'" onmouseout="document.but.src='icon1.gif'"> <IMG SRC="icon1.gif" NAME="but" WIDTH="100" HEIGHT="50" BORDER="0" ALT="..."> </A>

48 Image Change Using Functions
There are two important things in an image roll-over code. One is the image name and the other is the image source. Thus, we have to construct a function that accepts these two arguments and changes the image source. function roll_over(img_name, img_src) { document[img_name].src = img_src; } We can now call this function from our even handlers and pass it the two arguments. <A HREF="some.html" onmouseover="roll_over('but1', 'icon2.gif')" onmouseout="roll_over('but1', 'icon1.gif')"> <IMG SRC="icon1.gif" WIDTH="100" HEIGHT="50" NAME="but1" BORDER="0"> </A>

49 Switch Statement Use the switch statement to select one of many blocks of code to be executed. 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>

50 Revision By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript.  Examples of events: A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input field in an HTML form Submitting an HTML form A keystroke

51 Revision onLoad and onUnload
The onLoad and onUnload events are triggered when the user enters or leaves the page. The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.

52 Revision onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with validation of form fields. <input type="text" size="30" id=" " onchange="check ()">


Download ppt "JavaScript."

Similar presentations


Ads by Google