Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript. Introduction to Scripting Scripting Languages are mainly used to build the programming environment in HTML document Make Web pages dynamic.

Similar presentations


Presentation on theme: "JavaScript. Introduction to Scripting Scripting Languages are mainly used to build the programming environment in HTML document Make Web pages dynamic."— Presentation transcript:

1 JavaScript

2 Introduction to Scripting Scripting Languages are mainly used to build the programming environment in HTML document Make Web pages dynamic and interactive. Some languages : VBScript, JavaScript, Jscript. Browser Includes Scripting Interpreter Choosing a Scripting Language – Browser compatibility – Programmer familiarity Scripts can be executed on client or the server.

3 Client Vs. Server Scripting Client Side ScriptingServer Side Scripting Runs on the user’s computer i.e. Browser interprets the script Runs on the Web server Visible to users if they view the HTML source Not visible to user source Script is client side by defaultNeed to include RUNAT parameter RUNAT =“server” Reasons to use: Create control event procedures Reasons to use: Access server resources such as databases and hide business logic implementation Dynamic related functions.Database specific functions Data is already available at client- side Functions processed on server completely Subsequent processing has to be dynamically performed. e.g: Form Validation. Results to the client. e.g. Sorted data in combo

4 What is JavaScript?

5 Was designed to add interactivity to HTML pages Is a scripting language (a scripting language is a lightweight programming language) JavaScript code is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

6 What can a JavaScript do? JavaScript gives HTML designers a programming Tool JavaScript can put dynamic text into an HTML page JavaScript can react to events JavaScript can read and write HTML elements JavaScript can be used to validate input data JavaScript can be used to detect the visitor's browser JavaScript can be used to create cookies

7 How and Where Do You Place JavaScript Code?

8 How to put a JavaScript code into an HTML page? Use the tag (also use the type attribute to define the scripting language) …...

9 Where Do You Place Scripts? Scripts can be in the either section or section Convention is to place it in the section....

10 Referencing External JavaScript File Scripts can be provided locally or remotely accessible JavaScript file using src attribute <script language="JavaScript" type="text/javascript" src="http://somesite/myOwnJavaScript.js">

11 Deferred and Immediate Script Immediate mode implies that the code gets executed as the page loads. This can be done by keeping the SCRIPT tags in the BODY or by trapping the onload event. Deferred mode indicates that the script is executed based on some user action e.g. the clicking of the mouse or the pressing of a button.

12 JavaScript Language

13 JavaScript – lexical structure JavaScript is object based and action-oriented. JavaScript is case sensitive. A semicolon ends a JavaScript statement C-based language developed by Netscape Comments – Supports single line comments using // and multi line comments using /*…..*/

14 JavaScript Variable You create a variable with or without the var statement var strname = some value; strname = some value; When you declare a variable within a function, the variable can only be accessed within that function If you declare a variable outside a function, all the functions on your page can access it The lifetime of these variables starts when they are declared, and ends when the page is closed Keyword cannot be used as a variable name

15 Simple Program: Printing a line of Text in a Web Page A First Program in JavaScript Welcome to JavaScript Programming! " ); // -->

16 Simple Program: Printing a line of Text in a Web Page <!– document.write( " " ); document.write( "Welcome to JavaScript " + "Programming! " ); // -->

17 JavaScript Popup Boxes Alert box > User will have to click "OK" to proceed > window.alert("sometext"); Confirm box > User will have to click either "OK" or "Cancel“ to proceed > window.confirm("sometext"); Prompt box > User will have to click either "OK" or "Cancel" to proceed after entering an input value > window.prompt("sometext","defaultvalue");

18 Dynamic Welcome Page <!– var name; name = window.prompt( "Please enter your name", "GalAnt" ); document.writeln( " Hello " + name + ", welcome to JavaScript programming! " ); // --> Note: If we click on cancel button then it accept NaN.

19 JavaScript – Operators JavaScript operators may be classified into the following groups:  Arithmetic operator(+,-,*,/,%)  Logical operator(&&,||,!)  Relational operator(, =,!=)  Assignment operator(=,+=,*=,/=,%=)  Increment/Decrement operator(++,--)  Bitwise operator( >,&,|,^)  Conditional operator(?:)

20 Special Operators new – Used for instantiation of objects. – e.g: Date today = new Date( ); this – used to refer to the current object delete – The delete operator is used to delete an object, an object's property or a specified element in an array.

21 Algorithm Any computing problem can be solved by executing a series of actions in a specific order. A procedure for solving a problem in terms of 1. the actions to be executed, and 2. the order in which the actions are to be executed.Pseudocode Pseudocode is an artificial and informal language that helps programmers develop algorithms.

22 JavaScript – Control structures Control structure in JavaScript, as follows: – if Is used to conditionally execute a single block of code – if.. else a block of code is executed if the test condition evaluates to a boolean true else another block of code is executed. – switch …. case switch statement tests an expression against a number of case option executes the statements associated with the first match

23 JavaScript – Control structures while Repetition Statement for Repetition Statement do…while Repetition Statement switch Multiple-Selection Statement break and continue Statements Labeled break and continue Statements

24 Labled break stop: { // labeled block for ( var row = 1; row <= 10; ++row ) { if ( row == 5 ) break stop; // jump to end of stop block } document.writeln( " " ); } // the following line is skipped document.writeln( "This line should not print" );

25 Labled continue nextRow: // target label of continue statement for ( var row = 1; row <= 5; ++row ) { document.writeln( " " ); for ( var column = 1; column <= 10; ++column ) { if ( column > row ) continue nextRow; // next iteration of labeled loop document.write( "* " ); }

26 JavaScript: Functions A JavaScript function contains some code that will be executed only by an event or by a call to that function > To keep the browser from executing a script as soon as the page is loaded, you can write your script as a function You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external.js file). Functions can be defined either or section > As a convention, they are typically defined in the section

27 Example: JavaScript Function // If alert("Hello world!!") below had not been written within a // function, it would have been executed as soon as the page gets loaded. function displaymessage() { alert("Hello World!") // return can also be used in function definition } // return x; <input type="button" value="Click me!" onclick="displaymessage()" > // document.writeln(“The message is”+displaymessage() );

28 Random –Number Generation To generate numbers randomly random() method of Math object is used. Random method always return values between 0 and 1. 0≤ random()<1 Syntax: var=Math.floor(a+Math.random()*b); Where, a= shifting value(first value in the desired range) b= scaling factor(width of desired range)

29 Random-Image Generator <!-- document.write ( " " ); // -->

30 JavaScript Global Functions escape - this function takes a string argument and returns a string in which all spaces, punctuation and any other character that is not in the ASCII set are encoded in a hexadecimal format. unescape - this function takes a string argument and returns a string in which all characters previously encoded with escape are decoded. eval - This function evaluates a string of JavaScript code without reference to a particular object. e.g.: var ivalue = eval(“10*5+5”); ivalue will be assigned the value 55 after the execution of this statement.

31 JavaScript Global Functions isFinite - evaluates an argument to determine whether it is a finite number - The syntax of isFinite is: isFinite( number) where number is the number to evaluate. If the argument is NaN, positive infinity or negative infinity, this method returns false, otherwise it returns true. isNaN - Evaluates an argument to determine if it is “NaN” (not a number). - Returns true if the argument passed is not a number or false otherwise.

32 JavaScript Global Functions parseInt() - Converts a string value to an integer. parseInt() returns the first integer contained in a string. If the string does not begin with an integer, NaN (not a number) is returned. e.g.: var inum=parseInt(“ 1abc”); // returns 1 var inum= parseInt(“abc”); // returns NaN paresFloat( ) - The parseFloat method returns the first floating point number contained in string passed. If the srint does not begin with a floating point number, NaN (not a number) is returned. e.g: var fnum=parseFloat(“3.14abc”); // returns 3.14 var fnum= parseFloat(“abc”); // returns NaN

33 Recursion A recursion function is a function that calls itself, either directly, or indirectly through another function function fact(number) { if(number<=1) return 1; else return number * fact(number-1); }

34 JavaScript: Arrays Arrays are objects in JavaScript. Array can also be extended by referencing array elements outside the array. Declaring Arrays : – arrayname=new Array(array length); Constructing Dense Arrays: - var arrayname=new Arrray(val1,val2,..,valn); - var n=[1,2,3,4,5]; - var arr=[10,20,,30,40]; Length of an array can be calculated using length property. e.g.: n.length will give 5(size of an array n)

35 JavaScript: Arrays for…in statement - this statement enables a script to perform a task for each element in an array. syntax: for( var element in arrayname) arrayname[element]=0; Passing Array to Functions If array name has been declared as var name=new Array(25); then the function call fun(name); passes array name to function fun.

36 Random Image Generator using Arrays <!-- var pictures = [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ]; document.write ( "<img src = \"" + pictures[ Math.floor( Math.random() * 7 ) ] + ".gif\" width = \"105\" height = \"100\" />" ); // -->

37 Sorting Arrays Sorting is the method of putting data in some particular order, such as ascending or descending. To sort the elements of an array we sort method of an array object e.g.: var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; a.sort( compareIntegers ); outputArray( "Data items in ascending order: ", a ); function outputArray( header, theArray ) { document.writeln( " " + header + theArray.join( " " ) + " " ); } function compareIntegers( value1, value2 ) { return parseInt( value1 ) - parseInt( value2 ); }

38 Searching Arrays Linear Search - In this method we compare searching element with each element of an array,if match found then we return the position of element. Binary Search - In this we use divide the list of elements in two lists and than compare

39 Reading Values from Text field Enter integer search key var searchKey = parseInt(searchForm.inputVal.value);

40 Multidimensional Arrays Two dimensional array: creating 2-D array: var b; b=new Array(2); b[0]=new Array(5); b[1]=new Array(3); or var b=[ [1,2,3,4,5],[6,7,8] ]; join in 2-D array: for(var i in thearray) { for(var j in thearray[i]) thearray[i][j]=0; }

41 JavaScript: Objects JavaScript is based on object-based paradigm. Object is a construct with properties and methods. Any object should be instantiated before being used. Once instantiated, the properties and methods of the object can be used accordingly.

42 Creating objects Use the new operator to create an instance of a user-defined object type or of one of the predefined object types. To instantiate a standard object type e.g. var dtToday = new Date(); where Date() is an inbuilt object. JavaScript Built-in Objects: Math String Date Boolean Number Document window

43 Math Object Includes mathematical constants and functions. You do not need to create the Math object before using it. Usage : Math[.{property | method}] List of some commonly used methods (where x &y is are numbers) MethodsDescription abs(x)Return the absolute value of the x,e.g.: abs(-5.6)=5.6 sin(x)Returns the sine of x exp(x)Returns the value of E raised exp(x) to the power of x log(x)Returns the natural log of x max(x, y)Returns the number with the highest value of x and y sqrt(x)Returns the square root of x

44 Math Object MethodsDescription min(x,y)Returns the number with the minimum value of x and y round(x,y)Round x to the closest integer e.g.: round(9.75)=10.0 pow(x,y)X raised to power y (x y ) floor(x)Round x to the largest integer not greater than x e.g.: floor(9.2)=9.0, floor(-9.2)= -10.0 ceil(x)Round x to the smallest integer not less than x

45 Mathematical Constants ConstantDescriptionValue Math.EBase of a natural logarithm(e)Approx. 2.718 Math.LN2Natural logarithm of 2Approx. 0.693 Math.LN10Natural logarithm of 10Approx. 2.302 Math.LOG2EBase 2 logarithm of eApprox. 1.442 Math.LOG10EBase 10 logarithm of eApprox. 0.434 Math.PI π Approx. 3.1415926 Math.SQRT1_2Square root of 0.5Approx. 0.707 Math.SQRT2Square root of 2Approx. 1.414

46 String Object This object provides useful methods to manipulate strings – s1 = “infy" //creates a string literal value – s2 = new String(“infy") //creates a String object A String object has two types of methods: – Methods that return a variation on the string itself, such as substring and toUpperCase, – Those that return an HTML-formatted version of the string, such as bold and link.

47 String Object MethodDescription charAt(index)Return the character at the specified position in string charCodeAt(index)Return the character code at the specified position in string indexOf(sbstr,index)Return the position of specified substring in the string lastIndexOf(sbstr, index) Return the last position of specified substring in the string concat(string)Combines the text of two strings and returns a new string fromCharCode(v1,v2, v2,…….) Converts a list of Unicode values into a string containing corresponding characters slice(start, end)Returns a string containing the portion of the string from start through end, end=-1 indicate the end position of string. split(string)Splits the source string into an array of strings(tokens) where string is the delimiter.

48 String Object MethodDescription substr(start, length) Returns a string from source string from start to length. substring(start, end) Returns a string containing the portion of the string from start through end but excluding index end toLowerCase(), toUpperCase() Return the string in all lowercase or all uppercase, respectively toString(), valueOf() Returns the same string as the source string

49 Methods that generates XHTML tags MethodDescription anchor(name1)Wraps the source string in an anchor element( ) with with name1 as the anchor name. text blink()Wraps the source string in a element fixed()Wraps the source string in a element link(url)Wraps the source string in an anchor element( ) with url as the hyperlink location. click strike()Wraps the source string in a element sub()Wraps the source string in a element sup()Wraps the source string in a element

50 Date Object The Date object is used to work with dates and times. First we create the instance of objects. var time = new Date(); // object will contain todays date var hour = time.getHours() var minute = time.getMinutes() var second = time.getSeconds()

51 Date Object MethodDescription getDate()Returns the day of the month (Range is 1-31) getFullYear()Returns year in full 4 digit format (ie: 2004). getYear()Returns the year, in 2 digit format getMonth()Returns the month. (Range is 0-11)! getDay()Returns the day of the week (Range is 0-6). 0=Sunday, 1=Monday, etc. getHours()Returns the hour (Range is 0-23). getMinutes()Returns the minutes. (Range is 0-59). getSeconds()Returns the seconds. (Range is 0-59). getMilliseconds()Returns the milliseconds. (Range is 0-999). getTime()Returns the millisecond representation of the current Date object. In the words, the number of milliseconds between 1/1/1970 (GMT) and the current Date object.

52 Date Object MethodDescription getTimezoneOffset()Returns the offset (time difference) between Greenwich Mean Time (GMT) and local time of Date object, in minutes. getUTCFullYear()Returns the full 4 digit year in Universal time. getUTCMonth()Returns the month in Universal time. getUTCDate()Returns the day of the month in Universal time. getUTCDay()Returns the day of the week in Universal time. getUTCHours()Returns the hour in Universal time. getUTCMinutes()Returns the minutes in Universal time. getUTCSeconds()Returns the seconds in Universal time. getUTCMilliseconds()Returns the milliseconds in Universal time.

53 Date Object MethodDescription setFullYear(year, [month], [day]) Sets the year of the Date object. (year: 4 digit year). setMonth(month, [day]) Sets the month of the Date object. (month: 0-11) setDate(day_of_ month) Sets the day of the month of the Date object. (day_of_month: 1-31). setHours(hours, [minutes], [seconds], [millisec]) Sets the hour of the Date object. (hours: 0-23). setMinutes(minut es, [seconds], [millisec]) Sets the minutes of the Date object. (minutes: 0-59). setSeconds(secon ds, [millisec]) Sets the seconds of the Date object. (seconds: 0-59).

54 Boolean Object When JavaScript program requires boolean value,JavaScript automatically creates a Boolean object to store the value. JavaScript programmer can create Boolean objects explicitly with the statement var b=new Boolean(booleanValue); BooleanValue can be true or false, if BooleanValue is false,0,null,Number.NaN or an empty string(””), or if no argument is supplied, the new Boolean object contains false, otherwise the new Boolean object contains true. MethodDescription toString()Returns the string “true” if the value of the Boolean object is true; otherwise, return the string “false” valueOf()Returns the value true if the Boolean object is true; otherwise, return false

55 Number Object JavaScript automatically creates Number objects to store numeric values in a JavaScript program. JavaScript programmer can create Number objects explicitly with the statement var n=new Number(numericValue); Method or Property Description toString(radix)Returns the string representation of the number. Radix is the base of number MAX_VALUEThe largest representable number in JavaScript. MIN_VALUEThe smallest representable number in JavaScript. NaN"Not a number" value. NEGATIVE_INFINITY Negative infinity, returned on overflow. POSITIVE_INFINITY Infinity, returned on overflow.

56 document Object JavaScript provides the document object for manipulating the document that is currently visible in the window Method or Property Description write(string)Writes the string to the XHTML document as XHTML code. writeln(string)Writes the string to the XHTML document as XHTML code and adds a newline character at the end. document.cookieThis property is a string containing the values of all the cookies stored on the user’s computer for the current document. document.lastModifiedThis property is the date and time that this document was last modified.

57 window object JavaScript’s window object provides methods for manipulating browser windows. Method or PropertyDescription open(url,name,options)Creates a new window with the URL of the window set to url, the name set to name, and the visible features set by the string passed in as option prompt(prompt,default)Display dialog box asking the user for input close()Closes the current window and deletes its object focus()This method gives focus to the window blur()This method takes focus away from the window window.documentThis property contains the document object representing the document currently inside the window window.closedReturns true if window is closed else returns false window.opnerThis property contains the window object of the window that opened the current window

58 window object Open method childWindow = window.open( "", "", "resizable = " + resizable + ",toolbar = " + toolBar + ",menubar = " + menuBar + ",status = " + status + ",location = " + location + ",scrollbars = " + scrollBars ); To disable any button we use disabled property buttonname.disabled=false; childWindow.location will give you the string written in the URL of childWindow

59 Cookies A cookies is a piece of data that is stored on the user’s computer to maintain information about the client during and between browser sessions. To determine whether there is a cookie or not we can check by document. cookie. var myCookie = unescape( document.cookie ); var cookieTokens = myCookie.split( "=" ); name = cookieTokens[ 1 ]; document.cookie= "name=null;" + " expires=Thu, 01-Jan-95 00:00:01 GMT"; location.reload();

60 Thank You


Download ppt "JavaScript. Introduction to Scripting Scripting Languages are mainly used to build the programming environment in HTML document Make Web pages dynamic."

Similar presentations


Ads by Google