Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript.  A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as.

Similar presentations


Presentation on theme: "JavaScript.  A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as."— Presentation transcript:

1 JavaScript

2  A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as other programming languages (such as C and C++) are. Scripting languages, which can be embedded within HTML, commonly are used to add functionality to a Web page, such as different menu styles or graphic displays or to serve dynamic advertisements. These types of languages are client-side scripting languages, affecting the data that the end user sees in a browser window. Other scripting languages are server-side scripting languages that manipulate the data, usually in a database, on the server.high-level programming languageinterpretedruntimecompiledCC++HTMLdynamic clientbrowserserverdatabase  Scripting languages came about largely because of the development of the Internet as a communications tool. JavaScript, ASP, JSP, PHP, Perl, Tcl and Python are examples of scripting languages.JavaScriptASPJSPPHPPerlTclPython 2

3 JavaScript Basics  It is a Scripting Language invented by Netscape in 1995.  It is a client side scripting language. Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser, instead of server-side (on the web server). This type of computer programming is an important part of the Dynamic HTML (DHTML) concept, enabling web pages to be scripted; that is, to have different and changing content depending on user input, environmental conditions (such as the time of day), or other variablescomputer programswebexecutedclient-sideweb browserserver-side web servercomputer programmingDynamic HTMLweb pagesscripted  Sometimes JavaScript is referred to as ECMAscript, ECMA is European Computer Manufacturers Association, it is a private organization that develops standards in information and communication systems. 3

4 4 Understanding Javascript Javascript is used in million of web pages to Improve design Validate forms Detect browsers Create cookies, etc. Javascript is designed to add interactivity to HTML pages.

5 5 JavaScript Basics  Prerequisites for learning javascript. Knowledge of basic HTML. You need a web browser. You need a editor. No need of special h/w or s/w or a web server.

6 6 Understanding Javascript Javascript is a scripting language developed by Netscape. We can use nodepad, dreamweaver, golive etc. for developing javascripts.

7 7 HTML and Javascript  The easiest way to test a javascript program is by putting it inside an HTML page and loading it in a javascript enabled browser.  You can integrate javascript code into the HTML file in three ways  Integrating under tag  Importing the external javascript.

8 8 HTML and Javascript  Integrating script under the tag Javascript in the head section will execute when called i.e javascript in the HTML file will execute immediately while the web page loads into the web browser before anyone uses it.

9 9 HTML and Javascript  Integrating script under the tag  Syntax :- -----------------

10 10 HTML and Javascript  Integrating script under the tag When you place the javascript code under the tag, this generates the content of the web page. Javascript code executes when the web page loads and so in the body section.

11 11 HTML and Javascript  Integrating script under the tag  Syntax :- -----------------

12 12 HTML and Javascript  Importing the External javascript You can import an external javascript file when you want to run the same javascript file on several HTML files without having to write the same javascript code on every HTML file. Save the external javascript file with an extension.js The external javascript file don’t have a tag.

13 13 HTML and Javascript  Importing the external javascript  Syntax :- -----------------

14 14 First javascript program  The javascript code uses to start and end code.  The javascript code bounded with the script tags is not HTML to be displayed but rather script code to be processed.  Javascript is not the only scripting laguage, so you need to tell the browser which scripting language you are using so it knows how to process that language, so you specify

15 15 First javascript program  Including type attribute is a good practice but browsers like firefox, IE, etc. use javascript as their default script language, so if we don’t specify type attribute it assumes that the scripting language is javascript.  However use of type attribute is specified as mandatory by W3C.

16 16 First javascript program first javascript document.write(“First javascript stmt.”);

17 17 Elements of javascript  Javascript statement Every statement must end with a enter key or a semicolon. Example :- document.write(“First javascript stmt.”);

18 18 Elements of javascript  Javascript statement blocks Several javascript statement grouped together in a statement block. Its purpose is to execute sequence of statements together. Statement block begins and ends with a curly brackets.

19 19 Elements of javascript Example :- { document.write(“First javascript stmt.”); document.write(“Second javascript stmt.”); }

20 20 Elements of javascript  Javascript comments It supports both single line and multi line comments. // - Single line comments /*---------*/ - Multi line comments

21 21 Elements of javascript Example :- // javascript code { /* This code will write two statement in the single line. */ document.write(“First javascript stmt.”); document.write(“Second javascript stmt.”); }

22 22 Variables  Basic syntax of variable declaration Syntax:- var variablename;  Naming conventions Variable name can start with a alphabet or underscore. ( Rest characters can be number, alphabets, dollar symbol, underscore ) Do not use any special character other than dollar sign ($), underscore (_) Variable names are case-sensitive. Cannot contain blank spaces. Cannot contain any reserved word.

23 23 JavaScript Reserved Words abstract boolean break byte case catch char class const continue debugger default delete do double else enum export extends false final finally float for function goto if implements import in instanceof int interface long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with

24 24 Variables  Once you declare a variable you can initialize the variable by assigning value to it. Syntax:- variablename=value;  You can also declare and initialize the variable at the same time. Syntax:- var variablename=value;

25 25 Variables javascript variables var bookname=“web tech and applications”; var bookprice=390; document.write(“bookname is: ”,bookname); document.write(“bookprice is: ”,bookprice);

26 26 Datatypes  Javascript supports three primitive types of values and supports complex types such as arrays and objects. Number :consists of integer and floating point numbers.  Integer literals can be represented in decimal, hexadecimal and octal form.  Floating literal consists of either a number containg a decimal point or an integer followed by an exponent.

27 27 Datatypes  Boolean :consists of logical values true and false. Javascript automatically converts logical values true and false to 1 and 0 when they are used in numeric expressions.

28 28 Datatypes  String :consists of string values enclosed in single or double quotes.  Examples: var first_name=“Bhoomi”; var last_name=“Trivedi”; var phone=4123778; var bookprice=450.40;

29 29 Operators  Arithmetic operators OperatorAction +Adds two numbers together -Subtracts one number from another or changes a number to its negative *Multiplies two numbers together /Divides one number by another %Produces the remainder after dividing one number by another

30 30 Operators  Addition JavaScript can add together two or more numeric variables and/or numeric constants by combining them in an arithmetic expression with the arithmetic operator for addition ( + ). The result derived from evaluating an expression can be assigned to a variable for temporary memory storage. The following statements declare variables A and B and assign them numeric values; variable Sum is declared for storing the result of evaluating the arithmetic expression that adds these two variables. Example :- var A = 20; var B = 10; var Sum = A + B; var Sum1 = 1 + 2; var Sum2 = A + 2 + B + 1; var Sum3 = Sum1 + Sum2;

31 31 Operators  Other Arithmetic Operators OperatorAction ++X++ The equivalent of X = X + 1 ; add 1 to X, replacing the value of X --X-- The equivalent of X = X - 1 ; subtract 1 from X, replacing the value of X +=X += Y The equivalent of X = X + Y ; add Y to X, replacing the value of X -=X -= Y The equivalent of X = X - Y ; subtract Y from X, replacing the value of X *=X *= Y The equivalent of X = X * Y ; multiply Y by X, replacing the value of X /=X /= Y The equivalent of X = X / Y ; divide X by Y, replacing the value of X

32 32 Operators  Relational Operators Conditional Operator Comparison == Equal operator. value1 == value2 Tests whether value1 is the same as value2. != Not Equal operator. value1 != value2 Tests whether value1 is different from value2. < Less Than operator. value1 < value2 Tests whether value1 is less than value2. > Greater Than operator. value1 > value2 Tests whether value1 is greater than value2. <= Less Than or Equal To operator. value1 <= value2 Tests whether value1 is less than or equal to value2. >= Greater Than or Equal To operator. value1 >= value2 Tests whether value1 is greater than or equal to value2.

33 33 Operators  Logical Operators Logical Operator Comparison && And operator. condition1 && condition2 The condition1 and condition2 tests both must be true for the expression to be evaluated as true. || Or operator. condition1 || condition2 Either the condition1 or condition2 test must be true for the expression to be evaluated as true. ! Not operator. ! condition The expression result is set to its opposite; a true condition is set to false and a false condition is set to true.

34 34 If condition  Syntax:- if (conditional expression) { do this... }

35 35 If – else condition  Syntax:- if (conditional expression) { do this... } else { do this... }

36 36 Nested if condition  Syntax:- if (conditional expression) { if (conditional expression) { do this... } else { do this... } } else { if (conditional expression) { do this... } else { do this... } }

37 37 If..else if condition  Syntax:- if (conditional expression1) { do this... } else if (conditional expression2) { do this... } else if (conditional expression3) { do this... }... [else {do this...}]

38 38 The Switch Statement  Syntax:- switch (expression) { case "value1": do this... break case "value2": do this... break... [ default: do this... ] }

39 39 Iterations  For statement:- for (exp1;exp2;exp3) { do this... } exp1:initial expression exp2:conditional expression exp3:incremental expression

40 40 Iterations  while statement:- while (conditional expression) { do this... }

41 41 Iterations  do …. while statement do { do this... }while (conditional expression)

42 42 Array  Array is a javascript object that is capable of storing a sequence of values.  Array declaration syntax : var array-name = [item1, item2,...]; arrayname = new Array(); // var arrayname = []; arrayname = new Array(arraylength);  In the second syntax an array of size zero is created.  In the third syntax size is explicitly specified, hence this array will hold a pre-determined set of values.

43 43 Array  Examples of array declaration var cars = ["Saab", "Volvo", "BMW"]; var cars = new Array("Saab", "Volvo", "BMW");  Access the Elements of an Array var name = cars[0]; cars[0] = "Opel"; var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[10] = "Lemon"; // adds a new element (Lemon) to fruits

44 44 Array  Example :- bookname = new Array();  Note :- Even if array is initially created of a fixed length it may still be extended by referencing elements that are outside the current size of the array.  Example :- cust_order = new Array(); cust_order[50] = “Mobile”; cust_order[100] = “Laptop”;

45 45 Array  Dense Array It is an array that has been created with each of its elements being assigned a specific value. They are declared and initialized at the same time. Syntax:- arrayname = new Array(value0,value1,……..…,valuen);

46 46 Array  Array is a javascript object so it has several methods associated with it. join() – it returns all elements of the array joined together as a single string. By default “,” is used as a separator or you can specify the character to separate the array elements. reverse() – it reverses the order of the elements in the array.

47 47 Array  Array is a javascript object so it has also properties associated with it. length - it determines the total number of elements. Example :- length = myarray.length;  Javascript values for array could be of any type Example :- myarr = new Array(“one”,”two”,1,2, true, new Array(3,4) );

48 48 Special Operators  Strict Equal (= = =) Example “5” == 5 – true but “5” === 5 false It do not perform type conversion before testing for equality.  Ternary operators (? :) Example :- condition ? Exp1 : Exp2  Delete operator It is used to delete a property of an object or an element at an array index. Example :- delete arrayname[5]

49 49 Special Operators  New operator It is used to create an instance of object type. Example :- myarr = new Array();  Void operator It does not return a value It is specially used to return a URL with no value.

50 50 Functions  Functions are blocks of JS code that perform a specific task and often return a value.  Functions can be Built in functions User defined functions  Built in functions Examples :  eval()  parseInt()  parseFloat()

51 51 Functions  eval It is used to convert a string expression to a numeric value. Example :- var g_total = eval (“10 * 10 + 5”);  parseInt It is used to convert a string value to an integer. It returns the first integer contained in a string or “0” if the string does not begin with an integer. Example :- var str2no = parseInt(“123xyz”); //123 var str2no =parseInt(“xyz”);//NaN

52 52 Functions  parseFloat It returns the first floating point number contained in a string or “0” if the string does not begin with a valid floating point number. Example :- var str2no = parseFloat(“1.2xyz”); //1.2

53 53 Functions  User Defined functions When defining user defined functions appropriate syntax needs to be followed for  Declaring functions  Invoking / calling functions  Passing values  Returning and accepting the return values

54 54 Functions  Function Declaration Functions are declared and created using the function keyword. A function can comprise of the following things,  function name  List of parameters  Block of javascript code that defines what the function does. Syntax :- function function_name( P1, P2,………..,Pn) { //Block of JS code }

55 55 Functions  Place of declaration Functions can be declared any where within an HTML file. Preferably functions are created within the tags. This ensures that all functions will be parsed before they are invoked or called.

56 56 Functions  If the function is called before it is declared and parsed, it will lead to an error condition as the function has not been evaluated and the browser does not know that it exists.  Parsed:- it refers to the process by which the JS interpreter evaluates each line of script code and converts it into a pseudo – compiled byte code before attempting to execute it.  At this time syntax errors and other programming mistakes that would prevent the script from running are trapped and reported.

57 57 Functions  Function call A variable or a static value can be passed to a function. Example:- printName(“Bhoomi”); var firstname=“Bhoomi”; printName(firstname);

58 58 Functions  Variable Scope Any variable declared within the function is local to the function. Any variable declared outside the function is available to all the statements within the JS code.  Return Values Use return statement to return a value or expression that evaluates to a single value. function cube(n) { var ans = n * n * n; return ans; }

59 59 Functions  Recursive Functions A function calls itself. Example :- function factorial(n) { if ( n >1 ) return n * factorial(n-1); else return n; }

60 60 Dialog Boxes  Dialog Boxes JS provides the ability to pickup user input, display text to user by using dialog boxes. These dialog boxes appear as separate windows and their content depends on the information provided by the user. These content is independent of the text in the HTML page containing the JS code and does not affect the content of the page in any way. There are three types of dialog boxes provided by JS, Alert dialog box Prompt dialog box Confirm dialog box

61 61 Dialog Boxes  Alert dialog box It is used to display small amount of “textual output” to a browser window. The alert DB displays the string passed to the alert() as well as an OK button. It is used to display a “cautionary message” or “some information” for eg.  Display message when incorrect information is keyed in a form.  Display an invalid result as an output of a calculation.  A warning that a service is not available on a given date/time.

62 62 Dialog Boxes  Syntax :- alert (“message”);  Example :- alert(“This is a alert dialog box”); document.write(“Hello”);

63 63 Alert Dialog Box : Example

64 64 Dialog Boxes  Prompt Dialog Box Alert DB simply displays information in the browser and does not allow any interaction. It halts program execution until some action takes place. (i.e. click OK button) But it cannot be used to take input from user and display output based on it. For this we use prompt DB.

65 65 Dialog Boxes  Prompt Dialog Box Prompt() display the following things  A predefined message.  A textbox ( with a optional value)  A OK and CANCEL button. It also causes program execution to halt until action takes place. (i.e OK or CANCEL )  Clicking OK causes the text typed inside the textbox to be passed to the program environment.  Clicking CANCEL causes a Null value to be passed to the environment.

66 66 Dialog Boxes  Prompt Dialog Box Syntax :- prompt( “msg”,” ”); Example :- var name; name=prompt(“Enter you Name: ”,” “ “); document.write(“ Name entered is : ”,name);

67 67 Prompt Dialog Box : Example

68 68 Dialog Boxes  Confirm Dialog Box Confirm() display the following things  A predefined message.  A OK and CANCEL button. It also causes program execution to halt until action takes place. (i.e OK or CANCEL )  Clicking OK causes true to be passed to the program, which called Confirm DB.  Clicking CANCEL causes false to be passed to the program which called Confirm DB.

69 69 Dialog Boxes  Confirm Dialog Box Syntax :- confirm( “message”); Example :- var ans; ans=confirm(“Are you sure want to exit ? “); if ( ans == true ) document.write(“ you pressed OK”); else document.write(“ you pressed CANCEL”);

70 70 Confirm Dialog Box : Example

71 Different types of Objects  W3C DOM objects In recent browsers several objects are made available to allow more control over a document. Eg :- navigator, window, document, form, etc.  Built-in objects Several objects are part of JS language itself. These include the date, string and math objects.  Custom objects JS allows you to create your own objects that can contain related functionality.

72 JavaScript Object Hierarchy

73 W3C DOM objects  To access a documents property or method the general syntax is as follows, objectname.property objectname.method()  Document object Property :- alinkcolor, bgcolor, fgcolor, lastmodified, linkcolor, referrer, title, vlinkcolor.  Example :- document.lastModified Method :- write(str), writeln(str)

74 W3C DOM objects  Form object Property :- action, method, length, name, target  action- it points to the address of a program on the web server that will process the form data captured and being sent back.  method – it is used to specify the method used to send data captured by various form elements back to the web server. Method :- reset(), submit()

75 75

76 HTML form elements  text – a text field ( )  password – a password field in which keystrokes appear as an asterisk ( )  button – it provides a button other than submit and reset. ( )  checkbox – a checkbox. ( )  radio – a radio button. ( )

77 HTML form elements  reset – a reset button ( )  submit – a submit button ( )  select – a selection list. ( option1 option2 )  textarea – a multiline text entry field. ( )  hidden – a field that may contain a value but is not displayed within a form. ( )

78 Properties of form elements Property Name Form element nameDescription nameText,password,texta rea,button,radio,che ckbox,select,submit, reset,hidden Indicates the name of the object. valueText,password,texta rea,button,radio,che ckbox,select,submit, reset,hidden Indicates the current value of the object.

79 Properties of form elements Property NameForm element name Description defaultvalueText, password, textarea Indicates the default value of the object. checkedRadio button, checkbox Indicates the current status of the object. (checked/unchecked) defaultcheckedRadio button, checkbox Indicates the default status of the element.

80 Properties of form elements Property NameForm element name Description lengthRadioIndicates the number of radio buttons in the group. indexRadio button, select Indicates the index of currently selected radio button or option. textselectContains the value of the text.

81 Properties of form elements Property NameForm element name Description selectindexselectContains the index number of the currently selected option. defaultselectedselectIndicates whether the option is selected by default in the option tag selectedselectIndicates the current status of the option.

82 Events on form elements Method NameForm element name Description onFocus()Text, password,text area Fires when the form cursor enters into an object. onBlur()Text, password,text area Fires when the form cursor is moved away from an object. onSelect()Text, password,text area Fires when text is selected in an object.

83 Events on form elements Method NameForm element name Description onChange()Text, password,text area Fires when the text is changed in an object. onClick()Button, radio, checkbox, submit, reset Fires when an object is clicked on.

84 84 Events  Events Event HandlerEvent onclickThe mouse button is clicked and released with the cursor positioned over a page element. ondblclickThe mouse button is double-clicked with the cursor positioned over a page element. onmousedownThe mouse button is pressed down with the cursor positioned over a page element. onmousemoveThe mouse cursor is moved across the screen. onmouseoutThe mouse cursor is moved off a page element. onmouseoverThe mouse cursor is moved on top of a page element. onmouseupThe mouse button is released with the cursor positioned over a page element.

85 Example  Accept any mathematical expression evaluate and display the result. function calculate(form){ form.result.value=eval(form.entry.value); } Enter a mathematical expression

86 Built-in objects  String object  Date object  Math object

87 String object  Every string in an javascript is an object.  So it also has property and methods.  Property : length PropertyDescriptionReturns lengthReturns the number of characters in a string: TextString.length "A text string".length 13

88 MethodDescriptionReturns bold()Changes the text in a string to bold. TextString.bold() "A text string".bold() A text string italics()Changes the text in a string to italic. TextString.italics() "A text string".italics() A text string strike()Changes the text in a string to strike-through characters. TextString.strike() "A text string".strike() A text string sub()Changes the text in a string to subscript. "Subscript" + TextString.sub() "Subscript" + "A text string".sub() Subscript A text string sup()Changes the text in a string to superscript. "Superscript" + TextString.sup() "Superscript" + "A text string".sup() Superscript A text string toLowerCase()Changes the text in a string to lower-case. TextString.toLowerCase() "A text string".toLowerCase() a text string

89 toUpperCase()Changes the text in a string to upper-case. TextString.toUpperCase() "A text string".toUpperCase() A TEXT STRING fixed()Changes the text in a string to fixed (monospace) font. TextString.fixed() "A text string".fixed() A text string fontcolor ("color")Changes the color of a string using color names or hexadecimal values. TextString.fontcolor("blue") TextString.fontcolor("#0000FF") "A text string".fontcolor("blue") "A textstring".fontcolor("#0000FF") A text string fontsize("n")Changes the size of a string using font sizes 1 (smallest) - 7 (largest). TextString.fontsize("4") "A text string".fontsize("4") A text string link("href")Formats a string as a link. TextString.link("page.htm") "A text string".link("page.htm") A Text String

90 MethodDescriptionReturns charAt(index)Returns the character at position index in the string. TextString.charAt(0) "A text string".charAt(0) A charCodeAt(index)Returns the Unicode or ASCII decimal value of the character at position index in the string. TextString.charCodeAt(0) "A text string".charCodeAt(0) 65 indexOf("chars")Returns the starting position of substring "chars" in the string. If "chars" does not appear in the string, then -1 is returned. TextString.indexOf("text") "A text string".indexOf("text") TextString.indexOf("taxt") 2 2 -1 lastIndexOf("chars")Returns the starting position of substring "char" in the string, counting from end of string. If "chars" does not appear in the string, then -1 is returned. TextString.lastIndexOf("text") "A text string".lastIndexOf("text") TextString.lastIndexOf("taxt") 2 2 -1

91 substr(index[,length])Returns a substring starting at position index and including length characters. If no length is given, the remaining characters in the string are returned. TextString.substr(7,6) "A text string".substr(7,6) string substring(index1,index2)Returns a substring starting at position index1 and ending at (but not including) position index2. TextString.substring(7,13) "A text string".substring(7,13) string toString()Converts a value to a string. var NumberValue = 10 var StringValue = NumberValue.toString() 10 toFixed(n)Returns a string containing a number formatted to n decimal digits. var NumberValue = 10.12345 var StringValue = NumberValue.toFixed(2) 10.12 toPrecision(n)Returns a string containing a number formatted to n total digits. var NumberValue = 10.12345 var StringValue = NumberValue.toPrecision(5) 10.123

92 Math object  It has following properties E - Euler's constant LN2 - Natural log of the value 2 LN10 - Natural log of the value 10 LOG2E - The base 2 log of euler's constant (e). LOG10E - The base 10 log of euler's constant (e). PI - 3.1428 - The number of radians in a 360 degree circle (there is no other circle than a 360 degree circle) is 2 times PI. SQRT2 - The square root of 2.

93 Math object  It has following methods MethodDescriptionReturns Math.abs(expression)Returns the absolute (non-negative) value of a number: Math.abs(-100) 100 Math.max(expr1,expr2)Returns the greater of two numbers: Math.max(10,20) 20 Math.min(expr1,expr2)Returns the lesser of two numbers: Math.min(10,20) 10

94 Math object Math.round(expression)Returns a number rounded to nearest integer (.5 rounds up): Math.round(1.25) Math.round(1.50) Math.round(1.75) 122122 Math.ceil(expression)Returns the next highest integer value above a number: Math.ceil(3.25) 4 Math.floor(expression)Returns the next lowest integer value below a number: Math.floor(3.25)3 Math.pow(x,y)Returns the y power of x: Math.pow(2,3)8 Math.sqrt(expression)Returns the square root of a number: Math.sqrt(144)12 Math.random()Returns a random number between zero and one: Math.random() 0.039160

95 Date object MethodDescriptionReturns getDate()Returns the day of the month. TheDate.getDate()8 getDay()Returns the numeric day of the week (Sunday = 0). TheDate.getDay() 2 getMonth()Returns the numeric month of the year (January = 0). TheDate.getMonth() 6 getYear() getFullYear() Returns the current year. TheDate.getYear() TheDate.getFullYear()2014

96 Date object MethodDescriptionReturns getTime()Returns the number of milliseconds since January 1, 1970. TheDate.getTime() 1280911017797 getHours()Returns the military hour of the day. TheDate.getHours()14 getMinutes()Returns the minute of the hour. TheDate.getMinutes()6 getSeconds()Returns the seconds of the minute. TheDate.getSeconds()57 getMilliseconds()Returns the milliseconds of the second. TheDate.getMilliseconds()797

97 Date object MethodDescriptionReturns toTimeString()Converts the military time to a string. TheDate.toTimeString() 12:54:02 GMT+0530 (India Standard Time) toLocaleTimeString()Converts the time to a string. TheDate.toLocaleTimeString() 2:06:57 PM 9:45:48 AM toDateString()Converts the date to an abbreviated string. TheDate.toDateString() Tue Jul 08 2014 toLocaleDateString()Converts the date to a string. TheDate.toLocaleDateString() Tuesday, July 08, 2014 toLocaleString()Converts the date and time to a string. TheDate.toLocaleString() Tuesday, July 08, 2014 9:44:00 AM

98 Form Elements TextBox PropertiesMethodsEvents name value defaultValue focus() blur() select() onFocus() onBlur() onSelect() onChange() Password PropertiesMethodsEvents name value defaultValue focus() blur() select() onFocus() onBlur() onSelect() onChange()

99 Form Elements Button Submit Reset PropertiesMethodsEvents name value click()onClick()

100 Form Elements Checkbox PropertiesMethodsEvents name value checked defaulChecked click()onClick() Radio PropertiesMethodsEvents name checked index length click()onClick()

101 Form Elements Textarea PropertiesMethodsEvents name value defaultValue rows cols focus() blur() select() onFocus() onBlur() onSelect() Select and option Changa PropertiesMethodsEvents name text value selected index selectedIndex defaultSelected focus() blur() change() onFocus() onBlur() onChange()

102 Navigator object  The JavaScript navigator object is the object representation of the client internet browser or web navigator program that is being used. This object is the top level object to all others  Properties :- userAgent, appVersion, cookieEnabled  Methods :- javaEnabled(), tiantEnabled()  Navigator Objects Mime type Plugin Window

103 Window object  The JavaScript Window Object is the highest level JavaScript object which corresponds to the web browser window.  Internal Objects :- window, self, parent, top Window PropertiesMethodsEvents name length status defaultStatus alert() confirm() prompt() blur() close() focus() open() close() onBlur onClick onError onFocus onmouseout onmouseover onmouseup

104 History object  The JavaScript History Object is property of the window object.  Properties :- current, length, next, previous  Methods :- back(), forward(), go()  Example :-

105 Frame object  The JavaScript Frame object is the representation of an HTML FRAME which belongs to an HTML FRAMESET. The frameset defines the set of frame that make up the browser window. The JavaScript Frame object is a property of the window object. Document PropertiesMethodsEvents frames name length parent self blur() focus() setInterval() clearInterval() setTimeout(exp, milliseconds) clearTimeout(timeout) onBlur onFocus

106 Document object  The JavaScript Document object is the container for all HTML HEAD and BODY objects associated within the HTML tags of an HTML document. Document PropertiesMethodsEvents alinkcolor bgcolor, fgcolor, lastmodified, linkcolor, referrer, title, vlinkcolor write() open() close() contextual() onClick ondblclick ondragstart onkeydown onkeypress,onkeyup onmousedown,onmousemove onMouseOut,onMouseOver

107 Image object  The JavaScript Image Object is a property of the document object. Document PropertiesEvents border, complete height, hspace lowsrc, name. prototype, src vspace Width onAbort onError onLoad

108 Javascript Global  The JavaScript global properties and functions can be used with all the built-in JavaScript objects. PropertyDescription InfinityA numeric value that represents positive/negative infinity NaN"Not-a-Number" value undefinedIndicates that a variable has not been assigned a value

109 Javascript Global FunctionDescription decodeURI()Decodes a URI decodeURIComponent()Decodes a URI component encodeURI()Encodes a URI encodeURIComponent()Encodes a URI component escape()Encodes a string eval()Evaluates a string and executes it as if it was script code isFinite()Determines whether a value is a finite, legal number isNaN()Determines whether a value is an illegal number Number()Converts an object's value to a number parseFloat()Parses a string and returns a floating point number parseInt()Parses a string and returns an integer String()Converts an object's value to a string unescape()Decodes an encoded string

110 RegExp Object  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.  Regular expressions can be created in two ways as follows,  Syntax :- var txt= new RegExp(pattern,modifiers); var txt=/pattern/modifiers;

111 RegExp Object  Modifiers Modifiers are used to perform case-insensitive and global searches: ModifierDescription iPerform case-insensitive matching gPerform a global match (find all matches rather than stopping after the first match) mPerform multiline matching

112 RegExp Object  Brackets Brackets are used to find a range of characters: ExpressionDescription [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 uppercase A to uppercase Z [a-z]Find any character from lowercase a to lowercase z [A-z]Find any character from uppercase A to lowercase 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

113 RegExp Object  Metacharacters : Metacharacters are characters with a special meaning: MetacharacterDescription.Find a single character, except newline or line terminator \wFind a word character ( Matches any alphanumeric character including the underscore. Equivalent to [A-Za-z0-9_] ) \WFind a non-word character. Equivalent to [^A-Za-z0-9_] \dFind a digit. Equivalent to [0-9] \DFind a non-digit character \sFind a whitespace character. Matches a single white space character, including space, tab, form feed, line feed. Equivalent to [ \f\n\r\t\v ​ \u00a0\u1680 ​ \u180e\u2000 ​ \u2001\u2002 ​ \u2003\u2004 ​ \u2005\u2006 ​ \u2007\u2008 ​ \u2009\u200a ​ \u2028\u2029 ​​ \u202f\u205f ​ \u3000] \SFind a non-whitespace character \bFind a match at the beginning/end of a word \bton\b will find ton but not tons, but \bton will find tons. \BFind a match not at the beginning/end of a word \Bton\B will find wantons but not tons

114 RegExp Object MetacharacterDescription \0Find a NUL character \nFind a new line character \fFind a form feed character \rFind a carriage return character \tFind a tab character \vFind a vertical tab character \xxxFind the character specified by an octal number xxx \xddFind the character specified by a hexadecimal number dd \uxxxxFind the Unicode character specified by a hexadecimal number xxxx

115 RegExp Object  Quantifiers  * is short for {0,}. Matches zero or more times. + is short for {1,}. Matches one or more times. ? is short for {0,1}. Matches zero or one time. E.g: /o{1,3}/ matches 'oo' in "tooth" and 'o' in "nose". QuantifierDescription n+Matches any string that contains at least one n n*Matches any string that contains zero or more occurrences of n n?Matches any string that contains zero or one occurrences of n {n}Matches exactly n times. {n,}Matches n or more times. {n,m}Matches n to m times. n$Matches any string with n at the end of it ^nMatches any string with n at the beginning of it ?=nMatches any string that is followed by a specific string n ?!nMatches any string that is not followed by a specific string n

116 RegExp Object  Regular Expression Method DescriptionExample RegExp.exec(string) Applies the RegExp to the given string, and returns the match information. var match = /s(amp)le/i.exec("Sample text") match then contains ["Sample","amp"] RegExp.test(string) Tests if the given string matches the Regexp, and returns true if matching, false if not. var match = /sample/.test("Sample text") match then contains false String.match(pattern) Matches given string with the RegExp. With g flag returns an array containing the matches, without g flag returns just the first match or if no match is found returns null. var str = "Watch out for the rock!".match(/r?or?/g) str then contains ["o","or","ro"]

117 RegExp Object  Regular Expression Method DescriptionExample String.search(pattern) Matches RegExp with string and returns the index of the beginning of the match if found, -1 if not. var ndx = "Watch out for the rock!".search(/for/) ndx then contains 10 String.replace(pattern,string) Replaces matches with the given string, and returns the edited string. var str = "Liorean said: My name is Liorean!".replace(/Liorean/g,'Big Fat Dork') str then contains "Big Fat Dork said: My name is Big Fat Dork!" String.split(pattern) Cuts a string into an array, making cuts at matches. var str = "I am confused".split(/\s/g) s tr then contains ["I","am","confused"]

118 RegExp Object  Regular Expression Method function display() { var str="hello from CHARUSAT and hello from CMPICA".match(/hello/g); var str1=/hello/g.exec("hello from CHARUSAT and hello from CMPICA"); document.write(" match() : " +str+ " "); document.write(" exec() : " +str1+ " "); } match() : hello,hello exec() : hello

119 RegExp Object  Regular Expression Examples Test forRegular Expression No white space charater \S/; No alphabets, or hyphen, or period may appear in the string. /[^a-z \- \.] /gi ; No letters of digits may appear /[^a-z0-9]/gi ; 16 digit credit card number /^\d{4} ([ -]? \d{4} ){3}$ /

120 RegExp Object  Regular Expression Method function ver() { var b=/^\d{4}([\s-]+\d{4}){3}$/.test(f1.txtcredit.value); //var b=/^\d{4}([\s-]{1}\d{4}){3}$/.test(f1.txtcredit.value); if(b) alert("Valid Credit Card number."); else alert("Invalid Credit Card number."); } 1234 1231 1234 1547 1234-1234-1234-1547

121 RegExp Object  Regular Expression Examples US Zip code : Postal codes vary from country to country but in US they appear as either five numbers, or five numbers followed by a hyphen and four numbers.  97213  97213-1234  Regex : ^\d{5}(-\d{4})?$  US phone number : US phone number have a three-digit area code followed by seven more digits, however people write phone numbers in many different ways like  505-555-1212  (503) 555-1212  503.555.1212  503 555 1212  Regex : \(?(\d{3})\)?[ -.](\d{3})[ -.](\d{4})

122 Custom Object  Objects are useful to organize information.  An object is just a special kind of data, with a collection of properties and methods.  Example A person is an object. Properties are the values associated with the object. The persons' properties include name, height, weight, age, skin tone, eye color, etc. Objects also have methods. Methods are the actions that can be performed on objects. The persons' methods could be eat(), sleep(), work(), play(), etc.

123 Custom Object  Properties The syntax for accessing a property of an object is:  objName.propName You can add properties to an object by simply giving it a value. Assume that the personObj already exists - you can give it properties named firstname, lastname, age, and eyecolor as follows:  personObj.firstname=“Rajiv"; personObj.lastname=“Gandhi"; personObj.age=60; personObj.eyecolor="black"; document.write(personObj.firstname);

124 Custom Object  Methods An object can also contain methods. You can call a method with the following syntax:  objName.methodName() Note: Parameters required for the method can be passed between the parentheses. To call a method called sleep() for the personObj:  personObj.sleep();

125 Custom Object  Creating Your Own Objects There are different ways to create a new object: 1. Create a direct instance of an object The following code creates an instance of an object and adds four properties to it: personObj=new Object(); personObj.firstname=“Rajiv"; personObj.lastname=“Gandhi"; personObj.age=60; personObj.eyecolor="black";

126 Custom Object 2. Create a template of an object The template defines the structure of an object: function person(firstname, lastname, age, eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } Once you have the template, you can create new instances of the object, like this:  myson=new person(“Rahul",“Gandhi",30,"blue");  mydaughter=new person(“Priyanka",“Gandhi",32,"green");

127 Custom Object  You can also add some methods to the person object. This is also done inside the template: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.newlastname=newlastname; } Note that methods are just functions attached to objects. function newlastname(newln) { this.lastname=newln; }

128 Custom Object  Example Create an object :- Circle It has property :- radius It has methods :-  computearea()  computediameter() Note area = pi r 2 and diameter = radius * 2

129 Custom Object function circle(r){ this.radius=r; this.computearea=computearea; this.computediameter=computediameter; } function computearea(){ var area=this.radius * this.radius * 3.14; return area; } function computediameter(){ var diameter=this.radius * 2 ; return diameter; }

130 Custom Object var mycircle = new circle(20); alert("Area is " + mycircle.computearea()); alert("Diameter is " + mycircle.computediameter());

131 Try and Catch  The try...catch statement allows you to test a block of code for errors.  When browsing Web pages on the internet, we all have seen a JavaScript alert box telling us there is a runtime error and asking "Do you wish to debug?". Error message like this may be useful for developers but not for users. When users see errors, they often leave the Web page.  We will see how to catch and handle JavaScript error messages, so you don't lose your audience.

132 Try and Catch  The try...catch Statement The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Syntax :-try { //Run some code here } catch(err) { //Handle errors here } Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

133 Try and Catch var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue.\n\n"; alert(txt); } }

134 Try and Catch var txt=""; function message(){ try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.\n\n"; txt+="Click OK to continue viewing this page,\n"; txt+="or Cancel to return to the home page.\n\n"; if(!confirm(txt)) document.location.href="http://www.w3schools.com/"; } }

135 Try and Catch  JavaScript Throw Statement The throw statement allows you to create an exception. The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages. Syntax :-  throw(exception) The exception can be a string, integer, Boolean or an object. Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

136 Try and Catch var x=prompt("Enter a number between 0 and 10:",""); try { if(x>10) throw "Err1"; else if(x<0) throw "Err2"; else if(isNaN(x)) throw "Err3"; }

137 Try and Catch catch(er) { if(er=="Err1") alert("Error! The value is too high"); if(er=="Err2") alert("Error! The value is too low"); if(er=="Err3") alert("Error! The value is not a number"); }

138 JavaScript Special Characters  In JavaScript you can add special characters to a text string by using the backslash sign. Insert Special Characters The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters into a text string. var txt=“ Welcome to “CICA” which is a part of CHARUSAT” document.write(txt); var txt=“ Welcome to \“CICA\” which is a part of CHARUSAT” document.write(txt);

139 JavaScript Special Characters CodeOutputs \'single quote \"double quote \&ampersand \\backslash \nnew line \rcarriage return \ttab \bbackspace \fform feed

140 JavaScript For...In Statement  JavaScript For...In Statement  The for...in statement loops through the elements of an array or through the properties of an object.  Syntax  for (variable in object) { code to be executed }

141 JavaScript For...In Statement var x; var mycars = new Array(); mycars[0] = " BMW "; mycars[1] = "Volvo"; mycars[2] = “Santro"; for (x in mycars) document.write(mycars[x] + " ");

142 Referencing Elements  The other way of referencing elements is as follows,  Syntax :-  The assigned id value must be unique within the document; that is, no two tags can have the same id.  Also, the id value must be composed of alphabetic and numeric characters and must not contain blank spaces.

143 Referencing Elements  Once an id is assigned, then the HTML object can be referenced in a script using the notation as follows,  Syntax :- document.getElementById("id")

144 Getting and Setting Style Properties  The style properties associated with particular HTML tags are referenced by appending the property name to the end of the object referent.  Syntax :- Get a current style property: document.getElementById("id").style.property Set a different style property: document.getElementById("id").style.property = value

145 Getting and Setting Style Properties  Example :- This is a Heading document.getElementById("Head").style.color document.getElementById("Head").style.color = "red"

146 Applying Methods  Methods are behaviors that elements can exhibit, it can be referenced in a script using the notation as follows,  Syntax:- document.getElementById("id").method() Enter your name: document.getElementById("Box").focus()

147 Examples function ChangeStyle() { document.getElementById("MyTag").style.fontSize = "14pt"; document.getElementById("MyTag").style.fontWeight = "bold"; document.getElementById("MyTag").style.color = "red"; } This is a paragraph that has its styling changed.

148 Passing a Self Reference to a Function  Use of the self-referent keyword this can be combined with a function call to pass a self identity to a function.  Syntax :- eventHandler="functionName(this)“ function functionName(objectName) { objectName.style.property = "value"; objectName.style.property = "value"; }

149 Examples function ChangeStyle(Mytag) { MyTag.style.fontSize = "14pt"; MyTag.style.fontWeight = "bold"; MyTag.style.color = "red"; } This is a paragraph that has its styling changed.

150 Examples function ChangeStyle(Sometag) { Some Tag.style.fontSize = "14pt"; Some Tag.style.fontWeight = "bold"; Some Tag.style.color = "red"; } This is para1. This is para2.

151 HTML DOM Methods  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree-structure.

152 HTML DOM Methods  What is the DOM? The DOM is a W3C standard. The DOM defines a standard for accessing HTML and XML documents: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." The W3C DOM standard is separated into 3 different parts:  Core DOM - standard model for any structured document  XML DOM - standard model for XML documents  HTML DOM - standard model for HTML documents  What is the XML DOM? The XML DOM defines the objects and properties of all XML elements, and the methods to access them.  What is the HTML DOM? A standard object model for HTML (A W3C standard).A standard programming interface for HTML The HTML DOM defines the objects and properties of all HTML elements, and the methods to access them.In other words:The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

153 HTML DOM Methods DOM Tutorial DOM Lesson one Hello world!

154 HTML DOM Methods  Programming Interface The HTML DOM can be accessed with JavaScript (and other programming languages). All HTML elements are defined as objects, and the programming interface is the object methods and object properties. A method is an action you can do (like add or modify an element). A property is a value that you can get or set (like the name or content of a node).

155 HTML DOM Methods MethodDescription getElementById()Returns the element that has an ID attribute with the a value getElementsByTagName() Returns a node list (collection/array of nodes) containing all elements with a specified tag name getElementsByClassName()Returns a node list containing all elements with a specified class appendChild()Adds a new child node to a specified node removeChild()Removes a child node replaceChild()Replaces a child node insertBefore()Inserts a new child node before a specified child node createAttribute()Creates an Attribute node createElement()Creates an Element node createTextNode()Creates a Text node getAttribute()Returns the specified attribute value setAttribute()Sets or changes the specified attribute, to the specified value

156 HTML DOM Properties MethodDescription innerHTML The innerHTML property is useful for getting or replacing the content of HTML elements. nodeName The nodeName property specifies the name of a node. nodeValue The nodeValue property specifies the value of a node nodeType The nodeType property returns the type of node. nodeType is read only. ( Element, Attribute, Text, Comment, Document)

157 HTML DOM Methods  getElementById() Method The getElementById() method accesses the first element with the specified id Syntax : document.getElementById("id") Example : Alert innerHTML of an element with a specific ID: function getValue() { var x=document.getElementById("myHeader"); alert(x.innerHTML); } Click me!

158 HTML DOM Methods  getElementsByName() Method The getElementsByName() method accesses all elements with the specified name. Syntax : document.getElementsByName(name) Example : Alert the number of elements with a specific name: function getElements(){ var x=document.getElementsByName("x"); alert(x.length); } Cats: Dogs:

159 HTML DOM Methods  getElementsByTagName() Method The getElementsByTagName() method accesses all elements with the specified tagname. Syntax : document.getElementsByTagName(tagname)  function getElements() { var x=document.getElementsByTagName("input"); alert(x.length); }


Download ppt "JavaScript.  A high-level programming language that is interpreted by another program at runtime rather than compiled by the computer's processor as."

Similar presentations


Ads by Google