1 / 66

JavaScript

Learn about JavaScript, a scripting language used to add interactivity to HTML pages. Discover how to embed JavaScript code in HTML, place scripts in the head or body sections, reference external JavaScript files, and execute scripts on client or server.

lwarden
Download Presentation

JavaScript

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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

  4. What is JavaScript?

  5. What is JavaScript? • 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 YouPlace JavaScript Code?

  8. How to put a JavaScript code into an HTML page? • Use the <script> tag (also use the type attribute to define the scripting language) <html> <head> <script type="text/javascript"> … </script> </head> <body> <script type="text/javascript"> ... </script> </body> </html>

  9. Where Do You Place Scripts? • Scripts can be in the either <head> section or <body> section • Convention is to place it in the <head> section <html> <head> <script type="text/javascript"> .... </script> </head>

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

  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 onloadevent. • 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 varstrname = 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 <head> <title>A First Program in JavaScript</title> <script type = "text/javascript"> <!-- document.writeln( "<h1>Welcome to JavaScript Programming!</h1>" ); // --> </script> </head>

  16. Simple Program: Printing a line of Text in a Web Page <script type = "text/javascript"> <!– document.write( "<h1 style = \"color: magenta\">" ); document.write( "Welcome to JavaScript " + "Programming!</h1>" ); // --> </script>

  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 <script type = "text/javascript"> <!– var name; name = window.prompt( "Please enter your name", "GalAnt" ); document.writeln( "<h1>Hello " + name + ", welcome to JavaScript programming!</h1>" ); // --> </script> 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( "<br />" ); } // 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( "<br />" ); 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 .jsfile). • Functions can be defined either <head> or <body> section > As a convention, they are typically defined in the <head> section

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

  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 <script type = "text/javascript"> <!-- document.write ( "<imgsrc = \"" +Math.floor( 1 + Math.random() * 7 ) +".gif\" width = \"105\" height = \"100\" />" ); // --> </script>

  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.: varinum=parseInt(“ 1abc”); // returns 1 varinum= 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: varfnum=parseFloat(“3.14abc”); // returns 3.14 varfnum= 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: - vararrayname=new Arrray(val1,val2,..,valn); - var n=[1,2,3,4,5]; - vararr=[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 inarrayname) 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 <script type = "text/javascript"> <!-- var pictures = [ "CPE", "EPT", "GPP", "GUI", "PERF", "PORT", "SEO" ]; document.write ( "<imgsrc = \"" + pictures[ Math.floor( Math.random() * 7 ) ] + ".gif\" width = \"105\" height = \"100\" />" ); // --> </script>

  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( "<p>" + header + theArray.join( " " ) + "</p>" ); } 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 <body> <form name = "searchForm" action = ""> <p>Enter integer search key<br /> <input name = "inputVal" type = "text" /> <input name = "search" type = "button" value = "Search" onclick = "buttonPressed()" /><br /></p> </form> </body> varsearchKey = parseInt(searchForm.inputVal.value); <body onload=“start()”></body>

  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(vari 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. vardtToday = 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)

  44. Math Object

  45. Mathematical Constants

  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

  48. String Object

  49. Methods that generates XHTML tags

  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()

More Related