Java script final presentation

  • 3,487 views
Uploaded on

 

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
3,487
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
191
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1.
    • Building Web Sites: Introduction to JavaScript
    Kaushal Kishore Software Engineer OSSCube LLC [email_address] www.adhouraacademy.com
  • 2. What is JavaScript
      • JavaScript was originally developed by Brendan Eich of Netscape under the name  Mocha , which was later renamed to  LiveScript , and finally to JavaScript
      • A lightweight programming language that runs in a Web browser
      • JavaScript is a Client Side Scripting Language.
      • Also known as ECMAScript 
      • Interpreted, not compiled.
      • JavaScript Syntax are similar to C and Java Language.
      • JavaScript code is usually embedded directly into HTML pages
      • JavaScript is reasonably platform-independent
  • 3. What Can 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
  • 4. When not to use JavaScript
    • When you need to access other resources.
      • Files Programs
      • Databases
    • When you are using sensitive or copyrighted data or algorithms.
      • Your JavaScript code is open to the public .
  • 5. JavaScript is not Java
    • Java and JavaScript are two completely different languages in both concept and design!
    • JavaScript has some features that resemble features in Java:
      • JavaScript has Objects and primitive data types
      • JavaScript has qualified names; for example, document.write("Hello World");
      • JavaScript has Events and event handlers
      • Exception handling in JavaScript is almost the same as in Java
    • JavaScript has some features unlike anything in Java:
      • Variable names are untyped: the type of a variable depends on the value it is currently holding
      • Objects and arrays are defined in quite a different way
      • JavaScript is an interpreted language but java is both interpreted and compiled
  • 6. Where Do You Place Scripts?
    • JavaScript can be put in the <head> or in the <body> of an HTML document
      • JavaScript functions should be defined in the <head>
        • This ensures that the function is loaded before it is needed
      • JavaScript in the <body> will be executed as the page loads
    • JavaScript can be put in a separate .js file
      • <script src=&quot;myJavaScriptFile.js&quot;></script>
      • Put this HTML wherever you would put the actual JavaScript code
      • An external .js file lets you use the same JavaScript on multiple HTML pages
      • The external .js file cannot itself contain a <script> tag
    • JavaScript can be put in HTML form object, such as a button
      • This JavaScript will be executed when the form object is used
  • 7. Referencing External JavaScript File
    • Scripts can be provided locally or remotely accessible JavaScript file using src attribute
        • <html>
        • <head>
        • <script language=&quot;JavaScript“ type=&quot;text/javascript“ src=&quot;http://somesite/myOwnJavaScript.js&quot;>
        • </script>
        • <script language=&quot;JavaScript“ type=&quot;text/javascript“ src=&quot;myOwnSubdirectory/myOwn2ndJavaScript.js&quot;>
        • </script>
  • 8. Primitive Datatypes
    • JavaScript has three “primitive” types: number , string , and boolean
    • Numbers are always stored as floating-point values
      • Hexadecimal numbers begin with 0x
      • Some platforms treat 0123 as octal, others treat it as decimal
    • Strings may be enclosed in single quotes or double quotes
      • Strings can contains n (newline), &quot; (double quote), etc.
    • Booleans are either true or false
      • 0 , &quot;0&quot;, empty strings, undefined , null , and NaN are false , other values are true
  • 9. JavaScript Variable
    • You create a variable with or without the “var” statement
        • var num = “1”;
        • var name = “Kaushal”;
        • var phone = “123-456-7890”;
    • Variables names must begin with a letter or underscore
    • Variable names are case-sensitive
    • Variables are untyped (they can hold values of any type)
    • The word var is optional (but it’s good style to use it)
    • Variables declared within a function are local to that function (accessible only within that function)
    • Variables declared outside a function are global (accessible from anywhere on the page)
  • 10. Comments
    • Comments are as in C or Java:
      • Single Line Comment //
      • Paragraph Comment /*….*/
    • Java’s javadoc comments, /** ... */, are treated just the same as /* ... */ comments ; they have no special meaning in JavaScript
  • 11. Operators of JavaScript 1
    • Because most JavaScript syntax is borrowed from C (and is therefore just like Java), we won’t spend much time on it
    • Arithmetic operators: + - * / % ++ --
    • Comparison operators: < <= == != >= >
    • Logical operators: && || ! (&& and || are short-circuit operators)
    • Bitwise operators: & | ^ ~ << >> >>>
    • Assignment operators: += -= *= /= %= <<= >>= >>>= &= ^= |=
  • 12. Operators of JavaScript 2
    • String operator: +
    • The conditional operator: condition ? value_if_true : value_if_false
    • Special equality tests:
      • == and != try to convert their operands to the same type before performing the test
      • === and !== consider their operands unequal if they are of different types
    • Additional operators (to be discussed): new typeof void delete
  • 13. JavaScript Conditional Statements
    • In JavaScript we have the following conditional statements:
      • if statement
      • if...else statement
      • if...else if....else statement
      • s witch statement
  • 14. JavaScript Looping Statement
    • while 
        • Syntax:
        • while ( condition ) { code to be executed }
    • d o...while
        • Syntax:
        • do { code to be executed } while ( condition )
    • For
        • Syntax:
          • for ( initialization ; condition ; increment )
          • { code to be executed }
    • For…in
        • Syntax:
        • for ( variable  in  object )
        • { code to be executed }
  • 15. Example of for..in Statement
    • <html>
    • <body>
    • <script>
    • var person={fname:&quot;John&quot;,lname:&quot;Doe&quot;,age:25};
      • for (x in person)
      • {
      • document.write(person[x] + &quot; &quot;);
      • }
    • </script>
    • </body>
    • </html>
  • 16. Array Literals
    • You don’t declare the types of variables in JavaScript
    • JavaScript has array literals, written with brackets and commas
      • Example: color = [&quot;red&quot;, &quot;yellow&quot;, &quot;green&quot;, &quot;blue&quot;];
      • Arrays are zero-based: color[0] is &quot;red&quot;
    • If you put two commas in a row, the array has an “empty” element in that location
      • Example: color = [&quot;red&quot;, , , &quot;green&quot;, &quot;blue&quot;];
        • color has 5 elements
      • However, a single comma at the end is ignored
        • Example: color = [&quot;red&quot;, , , &quot;green&quot;, &quot;blue”,]; still has 5 elements
  • 17. Four ways to create an Array
    • You can use an array literal: var colors = [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;];
    • You can use new Array() to create an empty array:
        • var colors = new Array();
        • You can add elements to the array later:
        • colors[0] = &quot;red&quot;; colors[2] = &quot;blue&quot;; colors[1]=&quot;green&quot;;
    • You can use new Array(n) with a single numeric argument to create an array of that size
      • var colors = new Array(3);
    • You can use new Array(…) with two or more arguments to create an array containing those values:
      • var colors = new Array(&quot;red&quot;,&quot;green&quot;, &quot;blue&quot;);
  • 18. The length of an array
    • If myArray is an array, its length is given by myArray.length
    • Array length can be changed by assignment beyond the current length
      • Example: var myArray = new Array(5); myArray[10] = 3;
    • Arrays are sparse, that is, space is only allocated for elements that have been assigned a value
      • Example: myArray[50000] = 3; is perfectly OK
      • But indices must be between 0 and 2 32 -1
    • As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]
  • 19. Arrays and objects
    • Arrays are objects
    • car = { myCar: &quot;Saturn&quot;, 7: &quot;Mazda&quot; }
      • car[7] is the same as car.7
      • car.myCar is the same as car[&quot;myCar&quot;]
    • If you know the name of a property, you can use dot notation: car.myCar
    • If you don’t know the name of a property, but you have it in a variable (or can compute it), you must use array notation: car.[&quot;my&quot; + &quot;Car&quot;]
  • 20. Array functions
    • If myArray is an array,
      • myArray.sort() sorts the array alphabetically
      • myArray.reverse() reverses the array elements
      • myArray.push(…) adds any number of new elements to the end of the array, and increases the array’s length
      • myArray.pop() removes and returns the last element of the array, and decrements the array’s length
      • myArray.toString() returns a string containing the values of the array elements, separated by commas
  • 21. Exception Handling 1
    • Exception handling in JavaScript is almost the same as in Java
    • throw expression creates and throws an exception
      • The expression is the value of the exception, and can be of any type (often, it's a literal String)
    • try { statements to try } catch (e) { // Notice: no type declaration for e exception-handling statements } finally { // optional, as usual code that is always executed }
      • With this form, there is only one catch clause
  • 22. Exception Handling 2
    • try { statements to try } catch (e if test1) { exception-handling for the case that test1 is true } catch (e if test2) { exception-handling for when test1 is false and test2 is true } catch (e) { exception-handling for when both test1and test2 are false } finally { // optional, as usual code that is always executed }
    • Typically, the test would be something like e == &quot;InvalidNameException&quot;
  • 23. JavaScript Popup Boxes
    • Alert box
        • User will have to click &quot;OK&quot; to proceed
        • alert(&quot;sometext&quot;)
    • Confirm box
        • User will have to click either &quot;OK&quot; or &quot;Cancel&quot; to proceed
        • confirm(&quot;sometext&quot;)
    • Prompt box
      • User will have to click either &quot;OK&quot; or &quot;Cancel&quot; to proceed after entering an input value
      • prompt(&quot;sometext&quot;,&quot;defaultvalue&quot;)
  • 24. JavaScript Functions
    • JavaScript functions are created by the help of “function” keyword.
      • Syntax:
        • function function_name(arguments) {statement here}
    • 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 <head> or <body> section. As a convention, they are typically defined in the <head> section
  • 25. Example: JavaScript Function
    • <html>
    • <head>
      • <script type=&quot;text/javascript&quot;>
        • function displaymessage() {
        • alert(&quot;Hello World!&quot;)
        • }
      • </script>
    • </head>
    • <body>
    • <form>
    • <input type=&quot;button&quot; value=&quot;Click me!“ onclick=&quot;displaymessage()&quot; >
    • </form>
    • </body>
    • </html>
  • 26. Events & Event Handlers
    • Every element on a web page has certain events which can trigger invocation of event handlers
    • Attributes are inserted into HTML tags to define events and event handlers
    • Examples of events
      • A mouse click
      • A web page or an image loading
      • Mouse over a hot spot on the web page
      • Selecting an input box in an HTML form
      • Submitting an HTML form
      • A keystroke
  • 27. Events
    • onabort - Loading of an image is interrupted
    • onblur - An element loses focus
    • onchange - The content of a field changes
    • onclick - Mouse clicks an object
    • ondblclick - Mouse double-clicks an object
    • onerror - An error occurs when loading a document or an image
    • onfocus - An element gets focus
    • onkeydown - A keyboard key is pressed
    • onkeypress - A keyboard key is pressed or held down
    • onkeyup - A keyboard key is released
    • onload - A page or an image is finished loading
    • onmousedown - A mouse button is pressed
    • onmousemove - The mouse is moved
  • 28. Events
    • onmouseout - The mouse is moved off an element
    • onmouseover - The mouse is moved over an element
    • onmouseup - A mouse button is released
    • onreset - The reset button is clicked
    • onresize - A window or frame is resized
    • onselect - Text is selected
    • onsubmit - The submit button is clicked
    • onunload - The user exits the page
  • 29. onSubmit
    • The onSubmit event is used to validate all form fields before submitting it.
    • Example: The checkForm() function will be called when the user clicks the submit button in the form. If the field values are not accepted, the submit should be canceled. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled:
        • <form method=&quot;post&quot; action=&quot;xxx.html“ onsubmit=&quot;return checkForm() &quot;>
  • 30. Example & Demo: onSubmit
    • <html>
      • <head>
        • <script type=&quot;text/javascript&quot;>
          • function validate() {
          • // return true or false based on validation logic
          • }
        • </script>
      • </head>
    • <body>
    • <form action=&quot;tryjs_submitpage.htm&quot; onsubmit=&quot;return validate()&quot;>
      • Name (max 10 chararcters): <input type=&quot;text&quot; id=&quot;fname&quot; size=&quot;20&quot;><br />
      • Age (from 1 to 100): <input type=&quot;text&quot; id=&quot;age&quot; size=&quot;20&quot;><br />
      • E-mail: <input type=&quot;text&quot; id=&quot;email&quot; size=&quot;20&quot;><br />
      • <br />
      • <input type=&quot;submit&quot; value=&quot;Submit&quot;>
    • </form>
    • </body>
    • </html>
  • 31. Example & Demo: onblur
    • <html>
    • <head>
      • <script type=&quot;text/javascript&quot;>
        • function upperCase() {
          • var x=document.getElementById(&quot;fname&quot;).value
          • document.getElementById(&quot;fname&quot;).value=x.toUpperCase()
        • }
      • </script>
    • </head>
    • <body>
    • Enter your name:
    • <input type=&quot;text&quot; id=&quot;fname&quot; onblur=&quot;upperCase()&quot;>
    • </body>
    • </html>
  • 32. JavaScript Object
    • JavaScript is an Object Oriented Programming (OOP) language
    • A JavaScript object has properties and methods
      • Example: String JavaScript object has length property and toUpperCase() method
        • <script type=&quot;text/javascript&quot;>
          • var txt=&quot;Hello World!&quot;
          • document.write(txt.length)
          • document.write(txt.toUpperCase())
        • </script>
  • 33. JavaScript Built-in Objects
    • Array object
    • Boolean object
    • Date object
    • Math object
    • Number object
    • String object
    • Window object
    • Navigator object
    • Screen object
    • History object
    • Location object
  • 34. Creating Your Own JavaScript Objects
    • 3 different ways
      • Create a direct instance of an object by using built-in constructor for the Object class
      • Create a template (Constructor) first and then create an instance of an object from it
      • Create object instance as Hash Literal
  • 35. Option 1: Creating a Direct Instance of a JavaScript Object
    • By invoking the built-in constructor for the Object class
      • personObj=new Object(); // Initially empty with no properties or methods
    • Add properties to it
        • personObj.firstname=&quot;John&quot;;
        • personObj.age=50;
    • Add an anonymous function to the personObj
        • personObj.tellYourage=function(){
        • alert(“This age is ” + this.age);
        • }
        • // You can call then tellYourage function as following personObj.tellYourage();
  • 36. Option 1:Creating a Direct Instance of a JavaScript Object
    • Add a pre-defined function
        • function tellYourage(){
        • alert(“The age is” + this.age);
        • }
        • personObj.tellYourage=tellYourage;
    • Note that the following two lines of code are doing completely different things
        • // Set property with a function
        • personObj.tellYourage=tellYourage;
        • // Set property with returned value of the function
        • personObj.tellYourage=tellYourage();
  • 37. Option 2: Creating a template of a JavaScript Object
    • The template defines the structure of a JavaScript object in the form of a function
    • You can think of the template as a constructor
        • function Person(firstname,lastname,age,eyecolor) {
          • this.firstname=firstname;
          • this.lastname=lastname;
          • this.age=age;
          • this.tellYourage=function(){
            • alert(“This age is ” + this.age);
          • }
        • }
  • 38. Option 2: Creating a template of a JavaScript Object
    • Once you have the template, you can create new instances of the object
        • myFather=new Person(&quot;John&quot;,&quot;Doe&quot;,50,&quot;blue&quot;);
        • myMother=new Person(&quot;Sally&quot;,&quot;Rally&quot;,48,&quot;green&quot;);
    • You can add new properties and functions to new objects
        • myFather.newField = “some data”;
        • myFather.myfunction = function() {
        • alert(this[&quot;fullName&quot;] + ” is ” + this.age);
        • }
  • 39. Option 3: Creating JavaScript Object as a Hash Literal
    • Create personObj JavaScript object
        • var personObj = {
          • firstname: &quot;John&quot;,
          • lastname: &quot;Doe&quot;,
          • age: 50,
          • tellYourage: function () {
            • alert(“The age is ” + this.age );
          • }
          • tellSomething: function(something) {
            • alert(something);
          • }
        • }
      • personObj.tellYourage();
      • personObj.tellSomething(“Life is good!”);
  • 40. HTML DOM
    • The HTML DOM defines a standard set of objects for HTML, and a standard way to access and manipulate HTML documents
    • All HTML elements, along with their containing text and attributes, can be accessed through the DOM.
      • The contents can be modified or deleted, and new elements can be created.
    • JavaScript uses the HTML Document Object Model to manipulate HTML.
    • Levels of the DOM are dot-separated in the syntax.
  • 41. HTML DOM Objects
    • Anchor object
    • Document object
    • Event object
    • Form and Form Input object
    • Frame, Frameset, and IFrame objects
    • Image object
    • Location object
    • Navigator object
    • Option and Select objects
    • Screen object
    • Table, TableHeader, TableRow, TableData objects
    • Window object
  • 42. Document Tree Structure
  • 43. Document Object: Write text to the output
    • <html>
      • <body>
        • <script type=&quot;text/javascript&quot;>
        • document.write(“<h1>Hello World!</h1>&quot;)
        • </script>
      • </body>
    • </html>
  • 44. Document Object: Use getElementById()
    • <html>
    • <head>
      • <script type=&quot;text/javascript&quot;>
        • function getElement()
        • {
          • var x=document.getElementById(&quot;myHeader&quot;)
          • alert(&quot;I am a &quot; + x.tagName + &quot; element&quot;)
        • }
      • </script>
    • </head>
    • <body>
    • <h1 id=&quot;myHeader&quot; onclick=&quot;getElement()&quot;>Click to see what element I am!</h1>
    • </body>
    • </html>
  • 45. Document Object: Use getElementsByName()
    • <html>
      • <head>
        • <script type=&quot;text/javascript&quot;>
          • function getElements() {
          • var x=document.getElementsByName(&quot;myInput&quot;)
          • alert(x.length + &quot; elements!&quot;)
          • }
        • </script>
      • </head>
    • <body>
    • <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br />
    • <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br />
    • <input name=&quot;myInput&quot; type=&quot;text&quot; size=&quot;20&quot;><br />
    • <br />
    • <input type=&quot;button&quot; onclick=&quot;getElements()&quot; value=&quot;How many elements named 'myInput'?&quot;>
    • </body>
    • </html>
  • 46. Return the innerHTML of the first anchor in a document
    • <html>
    • <body>
      • <a name=&quot;first&quot;>First anchor</a><br />
      • <a name=&quot;second&quot;>Second anchor</a><br />
      • <a name=&quot;third&quot;>Third anchor</a><br />
      • <br />
      • InnerHTML of the first anchor in this document:
      • <script type=&quot;text/javascript&quot;>
      • document.write(document.anchors[0].innerHTML)
      • </script>
    • </body>
    • </html>
  • 47. Event Object: What are the coordinates of the cursor?
    • <html>
      • <head>
        • <script type=&quot;text/javascript&quot;>
        • function show_coords(event) {
        • x=event.clientX
        • y=event.clientY
        • alert(&quot;X coords: &quot; + x + &quot;, Y coords: &quot; + y)
        • }
        • </script>
      • </head>
    • <body onmousedown=&quot;show_coords(event)&quot;>
    • <p>Click in the document. An alert box will alert the x and y coordinates of the
    • cursor.</p>
    • </body>
    • </html>
  • 48. Event Object: What is the unicode of the key pressed?
    • <html>
      • <head>
        • <script type=&quot;text/javascript&quot;>
        • function whichButton(event) {
        • alert(event.keyCode)
        • }
        • </script>
      • </head>
    • <body onkeyup=&quot;whichButton(event)&quot;>
    • <p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>
    • <p>Press a key on your keyboard. An alert box will alert the unicode of the key
    • pressed.</p>
    • </body>
    • </html>
  • 49. Event Object: Which event type occurred?
      • <html>
      • <head>
        • <script type=&quot;text/javascript&quot;>
          • function whichType(event) {
          • alert(event.type)
          • }
        • </script>
      • </head>
      • <body onmousedown=&quot;whichType(event)&quot;>
      • <p>
      • Click on the document. An alert box will alert which type of event occurred.
      • </p>
      • </body>
      • </html>
  • 50. Questions
  • 51. Thank you for your Time and Attention! For more information visit http://adhouraacademy.com Or drop-in an email to kaushal.rahuljaiswal@gmail.com