Java Script basics and DOM

25
Java Script Sukrit Gupta [email protected]

description

 

Transcript of Java Script basics and DOM

Page 1: Java Script basics and DOM

Java Script

Sukrit [email protected]

Page 2: Java Script basics and DOM

JavaScript - Introduction

• Invented by Brendan Eich at Netscape, in1995.

• JavaScript is a programming language designed for Web pages.

• JAVASCRIPT is used to maintain BEHAVIOR of the document.• JavaScript is used in millions of Web pages to

improve the design, validate forms, detect browsers, create cookies, and much more.

• JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera.

• JavaScript is an interpreted language (means that scripts execute without preliminary compilation)

• Everyone can use JavaScript without purchasing a license • Unlike HTML, JavaScript is case sensitive.

Page 3: Java Script basics and DOM

Java≠JavaScript

Requires the JDK to create the applet

Requires a Java virtual machine to run the applet

Applet files are distinct from the HTML code

Source code is hidden from the user

Programs must be saved as separate files and compiled before they can be run

Programs run on the server side

Requires a text editor

Required a browser that can interpret JavaScript code

JavaScript can be placed within HTML and XHTML

Source code is made accessible to the user

Programs cannot write content to the hard disk

Programs run on the client side

Page 4: Java Script basics and DOM

Using JavaScript in a browser

• JavaScript code is included within <script> tags:• <script type="text/javascript">

document.write("<h1>Hello World!</h1>") ;</script>

• Notes:• The type attribute is to allow to use other scripting

languages (but JavaScript is the default)• This simple code does the same thing as just putting

<h1>Hello World!</h1> in the same place in the HTML document

• The semicolon at the end of the JavaScript statement is optional.

• We need semicolons if you put two or more statements on the same line.

Page 5: Java Script basics and DOM

Where to put JavaScript

• 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 functions can be put in a separate .js file• <script src="myJavaScriptFile.js"></script>• Put this in the <head>• An external .js file lets us use the same JavaScript on

multiple HTML pages• The external .js file cannot itself contain a <script> tag

• JavaScript can be put in an HTML form Object, such as a button• This JavaScript will be executed when the form object is used

Page 6: Java Script basics and DOM

JavaScript isn’t always available

• Some old browsers do not recognize script tags• These browsers will ignore the script tags but will display the

included JavaScript• To get old browsers to ignore the whole thing, use:

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

• The <!-- introduces an HTML comment• To get JavaScript to ignore the HTML close comment, -->, the //

starts a JavaScript comment, which extends to the end of the line

• Some users turn off JavaScript• Use the <noscript>message</noscript> to display a

message in place of whatever the JavaScript would put there

Page 7: Java Script basics and DOM

Writing Output to a Web Page

Manipulating HTML Elements

• <p id="demo">My First Paragraph</p>

<script>document.getElementById("demo").innerHTML="My First JavaScript";</script>

Writing to The Document Output

• <h1>My First Web Page</h1><script>

document.write("<p>My First JavaScript</p>");</script>

Page 8: Java Script basics and DOM

Variables

• Variables are declared with a var statement:• var pi = 3.1416, x, y, name = "Dr. Dave" ;• 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

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 9: Java Script basics and DOM

Variables

• Dynamic Typing - Variables can hold any valid type of value:– Number … var myInt = 7;– Boolean … var myBool = true;– Function …var fname= function() { ……. };– Object …... var person={firstname:"John", lastname:"Doe", id:5566};– Array ……. var myArr = new Array();– String …….var myString = “abc”;– … and can hold values of different types at different times during execution.

Page 10: Java Script basics and DOM

Operators

Arithmetic OperatorsAssignment Operators

Page 11: Java Script basics and DOM

OperatorsComparison Operators

Logical Operators

Page 12: Java Script basics and DOM

JavaScript Popup Boxes

Alert Box

An alert box is often used if we want to make sure information comes through to the user.

When an alert box pops up, the user will have to click "OK" to proceed.

<script>alert("Hello World!")</script>

Confirm Box A confirm box is often used if

we want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

• <script>confirm(“Sure??")</script>

Page 13: Java Script basics and DOM

JavaScript Popup Boxes

• Prompt Box• A prompt box is often used if we want the user to input a

value .• When a prompt box pops up, the user will have to click

either "OK" or "Cancel" to proceed after entering an input value.

• If the user clicks "OK“, the box returns the input value. If the user clicks "Cancel“, the box returns null.

• <script> var name=prompt("Please enter your name","Harry");</script>

Page 14: Java Script basics and DOM

Control and Looping

• ‘if’ statement• if ( boolean statement ) {…} else {…}

• ‘switch’ statement• switch ( myVar ) {• case 1: // if myVar is equal to 1 this is executed• break;• case “two”: // if myVar is equal to “two” this is executed• break;• case default: // if none of the cases above are satisfied OR if no• // ‘break’ statement are used in the cases above,• // this will be executed• }

Page 15: Java Script basics and DOM

Loops• The For Loop

• SYNTAX: for (start; condition; update) {JavaScript Commands}

• start is the starting value of the counter.• condition is a Boolean expression that must be true for

the loop to continue• update specifies how the counter changes in value each

time the command block is executed• Example for (var i=0; i<4; i++) { j++; }

• The While Loop• SYNTAX: while (condition) { JavaScript Commands}• condition is a Boolean expression that can be either true

or false• Example while (var i<=10) { j++; i++;}

• The Do While Loop• SYNTAX: do statement while (condition);

Page 16: Java Script basics and DOM

Functions• Functions should be defined in the <head> of an HTML page, to

ensure that they are loaded first• The syntax for defining a function is:

function fname(arg1, …, argN) { statements }• The function may return value.• Any variables declared within the function are local to it.• The syntax for calling a function is just

name(arg1, …, argN)• Simple parameters are passed by value, objects are passed by

reference• Function names are case-sensitive.• There is no limit to the number of function parameters that a

function may contain.

Page 17: Java Script basics and DOM

Objects• An object is just a special kind of data, with properties and

methods.• Almost everything in JavaScript is an Object: String, Number, Array,

Function, image.... Ex document.bgcolor• document is the object.• bgcolor is the property.

• We can also create our own objects:• SYNTAX: { name1 : value1 , ... , nameN : valueN }• EXAMPLE: car = {myCar: "Saturn", variant: "Mazda", special: Sales} • Example use: document.write("I own a " + car.myCar);

• Using new:• var course = new Object();

course.number = "CIT597";course.teacher = "Dr. Dave";

document.write(”Hello");document is the object.write is the method.

• Using a constructor:• function Course(n, t) { // best placed in <head>

this.number = n; // keyword "this" is required, this.teacher = t; //not optional

}• var course = new Course("CIT597", "Dr. Dave");

Page 18: Java Script basics and DOM

Event Handlers• Events are actions that occur usually as a result of something

the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a hyperlink.

• We write our scripts so they execute by reacting to events within a web browser.

• Since events are at the heart of JavaScript programming, we need a way to detect events. We do that by using built-in event handlers …

• Eg: Click, change, focus, load, mouseover, mouseout, reset, submit.

<input type=“button” onClick=“javascript:doButton()”>

• //calls function when button is clicked.

<body onLoad=“javascript:init()”>• //calls function when page is loaded.

Page 19: Java Script basics and DOM

Some more Events

Page 20: Java Script basics and DOM

DOM• DOM stands for Document Object

Model.• It 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 HTML DOM defines a standard for accessing and manipulating HTML documents.

• DOM is a tree of Objects• Contents can be modified or

deleted• New elements can be created and

inserted into the DOM Tree

Page 21: Java Script basics and DOM

document Object• The document object is the JavaScript interface to the DOM of

any HTML page.• Accessing elements:

– By name• document.getElementsByTagName(‘td')

[indexOfColumn];

• –By ID• document.getElementById('id');

• – Walk the DOM Tree•

document.childNodes[0].childNodes[1].childNodes[4];

Page 22: Java Script basics and DOM

Cookies

• JavaScript provides some limited, persistent storage, called cookies:

•– Data is stored in a text file on the client•– name=value•–Multiple values are delimited by a semicolon

• Use sparingly. There are limits (generally):•– Up to 300 cookies per browser, 20 cookies per web server, and 4 KB of data per cookie

• Don’t depend on cookies—users can block or delete them.

Page 23: Java Script basics and DOM

Cookies

• By default, cookies are destroyed when the browser window is closed, unless we explicitly set the expires attribute.• – To persist a cookie, set the expires attribute to a future date.• – To delete a cookie, set the expires attribute to a past date.

• By default, cookies can only be read by the web page that wrote them unless we specify one or more of these attributes:• – path – allows more than one page on the site to read a cookie.

(default value: /)• – domain – allows multiple servers to read a cookie.• -name – An identifier by which we reference a particular cookie.• -value – The information we wish to save, in reference to a particular

cookie.• -expires – A GMT-formatted date specifying the date (in milliseconds)

when a cookie will expire.

SYNTAX to create a cookie:• document.cookie = "username=" + who + ";” + "expires=" +

expDate.toGMTString();+ “path=/”

Page 24: Java Script basics and DOM

Tips for debugging JavaScript• Difficult because the language is interpreted.

• – No compiler errors/warnings.• – Browser will try to run the script, errors and all.

• Make each line as granular as possible (use variables).• Use alerts to get values of variables and see which lines

are not getting processed.• When testing form validation, set the action attribute to a

dummy HTML page—not the server-side form. If you get the page, the script works.

• Try add-on like Firebug to detect problem.• JavaScript is not totally platform independent

• – Expect different browsers to behave differently• – Check whether the browser supports the functionality or not.

Page 25: Java Script basics and DOM

Thank you!