51
Building Web Sites: Introduction to JavaScript Kaushal Kishore Software Engineer OSSCube LLC kaushal.rahuljaiswal@gmail .com www.adhouraacademy.com

Java script final presentation

Embed Size (px)

Citation preview

Page 1: Java script final presentation

Building Web Sites: Introduction to JavaScript

Kaushal Kishore

Software Engineer

OSSCube LLC

[email protected]

www.adhouraacademy.com

Page 2: Java script final presentation

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

Page 3: Java script final presentation

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

Page 4: Java script final presentation

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.

Page 5: Java script final presentation

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

Page 6: Java script final presentation

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="myJavaScriptFile.js"></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

Page 7: Java script final presentation

Referencing External JavaScript File

• Scripts can be provided locally or remotely accessible JavaScript file using src attribute

<html>

<head>

<script language="JavaScript“ type="text/javascript“ src="http://somesite/myOwnJavaScript.js">

</script>

<script language="JavaScript“ type="text/javascript“ src="myOwnSubdirectory/myOwn2ndJavaScript.js">

</script>

Page 8: Java script final presentation

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), \" (double quote), etc.

• Booleans are either true or false• 0, "0", empty strings, undefined, null, and NaN are false ,

other values are true

Page 9: Java script final presentation

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)

Page 10: Java script final presentation

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

Page 11: Java script final presentation

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: += -= *= /= %= <<= >>= >>>= &= ^= |=

Page 12: Java script final presentation

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

Page 13: Java script final presentation

JavaScript Conditional Statements

• In JavaScript we have the following conditional statements:• if statement • if...else statement • if...else if....else statement • switch statement

Page 14: Java script final presentation

JavaScript Looping Statement

• while • Syntax: • while (condition) { code to be executed }

• do...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 }

Page 15: Java script final presentation

Example of for..in Statement• <html>• <body>• <script> • var person={fname:"John",lname:"Doe",age:25};

– for (x in person)– {– document.write(person[x] + " ");– }

• </script>• </body>• </html>

Page 16: Java script final presentation

Array Literals

• You don’t declare the types of variables in JavaScript

• JavaScript has array literals, written with brackets and commas• Example: color = ["red", "yellow", "green", "blue"];• Arrays are zero-based: color[0] is "red"

• If you put two commas in a row, the array has an “empty” element in that location• Example: color = ["red", , , "green", "blue"];

• color has 5 elements• However, a single comma at the end is ignored

• Example: color = ["red", , , "green", "blue”,]; still has 5 elements

Page 17: Java script final presentation

Four ways to create an Array

• You can use an array literal: var colors = ["red", "green", "blue"];

• You can use new Array() to create an empty array:• var colors = new Array();• You can add elements to the array later:• colors[0] = "red"; colors[2] = "blue";

colors[1]="green";• 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("red","green", "blue");

Page 18: Java script final presentation

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 232-1

• As in C and Java, there are no two-dimensional arrays; but you can have an array of arrays: myArray[5][3]

Page 19: Java script final presentation

Arrays and objects

• Arrays are objects• car = { myCar: "Saturn", 7: "Mazda" }

• car[7] is the same as car.7• car.myCar is the same as car["myCar"]

• 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.["my" + "Car"]

Page 20: Java script final presentation

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

Page 21: Java script final presentation

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

Page 22: Java script final presentation

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 == "InvalidNameException"

Page 23: Java script final presentation

JavaScript Popup Boxes

• Alert box• User will have to click "OK" to proceed• alert("sometext")

• Confirm box• User will have to click either "OK" or "Cancel" to proceed• confirm("sometext")

• Prompt box• User will have to click either "OK" or "Cancel" to

proceed after entering an input value• prompt("sometext","defaultvalue")

Page 24: Java script final presentation

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

Page 25: Java script final presentation

Example: JavaScript Function

• <html>• <head>

– <script type="text/javascript">• function displaymessage() { • alert("Hello World!")• }

– </script>• </head>• <body>• <form>• <input type="button" value="Click me!“

onclick="displaymessage()" >• </form>• </body>• </html>

Page 26: Java script final presentation

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

Page 27: Java script final presentation

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

Page 28: Java script final presentation

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

Page 29: Java script final presentation

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="post" action="xxx.html“ onsubmit="return checkForm()">

Page 30: Java script final presentation

Example & Demo: onSubmit

• <html>– <head>

• <script type="text/javascript">– function validate() {– // return true or false based on validation logic– }

• </script>– </head>

• <body>• <form action="tryjs_submitpage.htm" onsubmit="return validate()">

– Name (max 10 chararcters): <input type="text" id="fname" size="20"><br />– Age (from 1 to 100): <input type="text" id="age" size="20"><br />– E-mail: <input type="text" id="email" size="20"><br />– <br />– <input type="submit" value="Submit">

• </form>• </body>• </html>

Page 31: Java script final presentation

Example & Demo: onblur

• <html>• <head>

– <script type="text/javascript">• function upperCase() {

– var x=document.getElementById("fname").value– document.getElementById("fname").value=x.toUpperCase()

• }– </script>

• </head>• <body>• Enter your name:• <input type="text" id="fname" onblur="upperCase()">• </body>• </html>

Page 32: Java script final presentation

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="text/javascript">

• var txt="Hello World!"

• document.write(txt.length)

• document.write(txt.toUpperCase())

• </script>

Page 33: Java script final presentation

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

Page 34: Java script final presentation

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

Page 35: Java script final presentation

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="John";• 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();

Page 36: Java script final presentation

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

Page 37: Java script final presentation

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

• }

• }

Page 38: Java script final presentation

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("John","Doe",50,"blue");• myMother=new Person("Sally","Rally",48,"green");

• You can add new properties and functions to new objects

• myFather.newField = “some data”;• myFather.myfunction = function() {• alert(this["fullName"] + ” is ” + this.age);• }

Page 39: Java script final presentation

Option 3: Creating JavaScript Object as a Hash Literal

• Create personObj JavaScript object• var personObj = {

• firstname: "John",• lastname: "Doe",• age: 50,• tellYourage: function () {

• alert(“The age is ” + this.age );• }• tellSomething: function(something) {

• alert(something);• }

• }

• personObj.tellYourage();• personObj.tellSomething(“Life is good!”);

Page 40: Java script final presentation

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.

Page 41: Java script final presentation

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

Page 42: Java script final presentation

Document Tree Structure

<html> <body> <h1>Heading 1</h1> <p>Paragraph.</p> <h2>Heading 2</h2> <p>Paragraph.</p> </body></html>

#text

H1

H2

P

BODY

HTML

#document

HEAD

#text

P

#text

#text

Page 43: Java script final presentation

Document Object: Write text to the output

• <html>– <body>

• <script type="text/javascript">• document.write(“<h1>Hello World!</h1>")• </script>

– </body>

• </html>

Page 44: Java script final presentation

Document Object: Use getElementById()

• <html>• <head>

– <script type="text/javascript">• function getElement() • {

– var x=document.getElementById("myHeader")– alert("I am a " + x.tagName + " element")

• }– </script>

• </head>• <body>• <h1 id="myHeader" onclick="getElement()">Click to see

what element I am!</h1>• </body>• </html>

Page 45: Java script final presentation

Document Object: Use getElementsByName()

• <html>– <head>

• <script type="text/javascript">– function getElements() {– var x=document.getElementsByName("myInput")– alert(x.length + " elements!")– }

• </script>– </head>

• <body>• <input name="myInput" type="text" size="20"><br />• <input name="myInput" type="text" size="20"><br />• <input name="myInput" type="text" size="20"><br />• <br />• <input type="button" onclick="getElements()" value="How many elements

named 'myInput'?">• </body>• </html>

Page 46: Java script final presentation

Return the innerHTML of the first anchor in a document

• <html>• <body>

– <a name="first">First anchor</a><br />– <a name="second">Second anchor</a><br />– <a name="third">Third anchor</a><br />– <br />– InnerHTML of the first anchor in this document:– <script type="text/javascript">– document.write(document.anchors[0].innerHTML)– </script>

• </body>• </html>

Page 47: Java script final presentation

Event Object: What are the coordinates of the cursor?

• <html>– <head>

• <script type="text/javascript">• function show_coords(event) {• x=event.clientX• y=event.clientY• alert("X coords: " + x + ", Y coords: " + y)• }• </script>

– </head>• <body onmousedown="show_coords(event)">• <p>Click in the document. An alert box will alert the x and y

coordinates of the• cursor.</p>• </body>• </html>

Page 48: Java script final presentation

Event Object: What is the unicode of the key pressed?

• <html>– <head>

• <script type="text/javascript">• function whichButton(event) {• alert(event.keyCode)• }• </script>

– </head>• <body onkeyup="whichButton(event)">• <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>

Page 49: Java script final presentation

Event Object: Which event type occurred?

– <html>– <head>

• <script type="text/javascript">– function whichType(event) {– alert(event.type)– }

• </script>– </head>– <body onmousedown="whichType(event)">– <p>– Click on the document. An alert box will alert which type of

event occurred.– </p>– </body>– </html>

Page 50: Java script final presentation

Questions

Page 51: Java script final presentation

Thank you for your Time and Attention!

51

For more information visit http://adhouraacademy.comOr drop-in an email to [email protected]