Está en la página 1de 20

JavaScript is an interpreted, object-based scripting language It is based on an object model.

JavaScript was created by Sun Microsystems and Netscape JavaScript makes it easier to create interactive Web pages Java Script is interpreted by the client browser. Previously it was known as Jscript. It is a programming language of the web and mainly used for validating forms. Java Script should be written between the <SCRIPT> AND </SCRIPT> tags. The value LANGUAGE=JavaScript indicates to the browser that Javascript code has been used in the HTML document. It is a good programming practice to include the java script code within the <HEAD> and </HEAD> tags. So when a javascript code element is encountered the browser executes the same and displays the results. Common Gateway Interface was considered as the standard for processing the forms. It was time consuming process because form validation used to take place on the server side. JavaScript made the entire work easier by validating the form at the client side. <HTML> <HEAD> <TITLE>HTML containing JAVASCRIPT</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE=JavaScript> document.write(First JavaScript Statement); </SCRIPT> </BODY> <HTML> Server sends entire contents of document to the client browser as and when client request for a page that contain JavaScript statements . <HTML> <HEAD> <TITLE>BUZZ OFF !!!</TITLE> <SCRIPT LANGUAGE=JavaScript> alert(Press Ok to start formatting your hard disk); </SCRIPT> </HEAD> </HTML>

Features of Java Script Scripting Language

Object Based and not Object Oriented Event Driven Platform Independent any browser Enable Quick Development Easy to Learn JavaScript is a scripting language. It is a hybrid between HTML and a programming language JavaScript is an extension of HTML. You can add JavaScript to your existing HTML documents by adding the <SCRIPT> tag

In order to use JavaScript efficiently, you need a browser that can take advantage of it such as Netscape Navigator 2.0 and above JavaScript can be used to write both client- side and server-side applications. Client applications run in a browser, For Example, Netscape Navigator or Internet Explorer Server applications run on a Web server For Example, Microsofts Internet Information Server. JavaScript is not ideal for writing Server-side scripts because of its limited power. But Netscape has a product called Live Wire which support server side java script code. But in our session, basically we deal with client side java script.

Only a browser that is java script enabled wiil be able to interpret JavaScript code. VARIABLE In Java Script variables can be created that can hold any type of data. The variable names are case sensitive. You can declare a variable with the var statement: Var strname=some value You can also declare a variable by simply assigning a value to the variable. Like strname=some value Life Span of Variables When you declare a variable within a function, the variable can be accessed only within the function. When you exit the function, the variable is destroyed. These variables are called local variables. If you declare a variable outside a function, all the functions on your page can access it. The life time these variables starts when they are declared, and ends when the page is closed. Variable names can begin with : Uppercase letter (A through Z), Lowercase letter (a through z), Underscore character (_), Dollar sign character ($). The remaining characters can consist of letters or digits (0 through 9). For example Sum1 , total ,qty2_1 , _count, Next_Count Variable names are case sensitive Variable names are case sensitive JavaScript does not require you to specify the type of the data contained in a variable JavaScript supports the following types of values Number This consists of numbers including both integer and floating-point. String This consists of text specified within single or double quotes. Null This consists of null value. Boolean This consists of Boolean values true and false Number Types Integers and Floating-Point Numbers : Integers can be represented in one of the following ways Number System Base Expressed as Example

Decimal

10

Sequence of digits without a leading 0

35, - 63

Octal

Sequence of digits with a leading 0

0377, 0568.

Hex

16

A leading 0x (or 0X) indicates hexadecimal

0xABC, 0X12

Alphanumeric data in JavaScript is known as String, String is one or more characters enclosed within single or double quotes. If a string begins with single quote then it has to end with a single quote For Example s1 = This is a sample string The quote characters ( or ) can be embedded in a string, but backslash (\) escape characters must precede the quote characters to suppress their meaning. For Example This is a string which displays \\ on the screen You must note that the escape characters work with <PRE> and </PRE> tags Character Meaning

Single Quote

Double Quote

\\

Backslash

\r

Carriage Return

\f

Form Feed

\n

New Line

\b

Backspace

\t

Tab

This can be used with all JavaScript types. The null value indicates that a variable is un-initialized

JavaScript supports a pure Boolean type It consists of two values true and false. JavaScript automatically converts true or false in to 1 or 0 Value 0 and 1 are not considered as Boolean in JavaScript.

Type Casting JavaScript automatically converts values from one type to another when they are used in expressions. Adding together the floating-point literal 7.5 and the string "12" results in the floating point numeric literal 19.5. This type of automatic conversion from one type to another is known as type casting In later versions of JavaScript, however, this kind of type casting is not supported Conversion Functions

Arrays An Array is a data structure used to store a set of values. Each element of an array can be referenced using an index. Every array has to be declared before it is used

For Example Student = new Array (5) arrayName = new Array ( ) For Example Days = new Array (Mon, Tue, Wed, Thu, Fri, Sat, Sun) JavaScript does not place any restrictions on the type of elements stored in an array Operators The set of operators that JavaScript uses is very similar to other programming languages. The operators can be classified as below: Assignment Comparison

Arithmetic Bitwise Logical String Special Operator acts upon certain values in order to produce a resultant value, whereas the values on which the operator acts in known as Operand. The combination of an operator and its operand is known as an Expression.

Special Operators Comma (,) operator The comma operator (,) evaluates two operands and returns the value of the second operand new & delete operators The delete operator is used to delete an objects property or an element at a specified index in an array. The new operator allows create an instance of an object typeof operator The typeof operator returns a string indicating the type of the operand void operator A void operator would cause no results to be returned to the program after an expression is evaluated Java Script Statements JavaScript programs can be made of single statements or a block of statements. The block of statements is enclosed in {and} brackets In which each statement can be separated by a semi-colon (;). There are several types of statements, which are as follows Assignment Statements Data Declaration Statements Switch Statements Conditional Statements Loop Statements <HTML> <HEAD> <TITLE> For Loop Sample </TITLE> <SCRIPT LANGUAGE = JavaScript> for (i= 1; i<=10; i++) { document.write(The Value Of i is + i) document.write(<BR>) } </SCRIPT> </HEAD> <BODY> <H1 ALIGN = CENTER> For Loop Sample Program </H1> </BODY> </HTML> Functions Functions are set of statements, which perform a specific task

Function name be preceded by the keyword function. Functions are not executed until they are explicitly called using function call statements HTML> <HEAD> <TITLE> Function </TITLE> <SCRIPT LANGUAGE = "JavaScript"> function Disp() //Function definition { document.write (Hello World) } Disp() //Function call </SCRIPT> </HEAD> <BODY> <H1 ALIGN = "CENTER"> How To Use Functions </H1> <SCRIPT LANGUAGE = "JavaScript"> for ( i=1; i<5; i++) { document.write("<BR>") Disp() //Function call } </SCRIPT> <BODY> </HTML> Function With Arguments The function Sum is defined in the head section and accepts two numbers num1, num2 to calculate the sum. <HTML> <HEAD> <TITLE> Sum Function </TITLE> <SCRIPT LANGUAGE = "JavaScript"> function Sum(num1, num2) { var ans = num1 + num2 document.write (The Sum Is + ans) } </SCRIPT> </HEAD> <BODY> <H1 ALIGN = "CENTER"> Function To Add Two Numbers</H1> <SCRIPT LANGUAGE = "JavaScript"> Sum (1,2) </SCRIPT> <BODY> </HTML> Function With variable Arguments JavaScript provides an array known as the arguments array, which keeps track of the arguments passed to a function. This array has an attribute called the length, which holds the number of arguments passed to a function

The arguments array can only be used with the function object <HTML> <HEAD> <TITLE> Sum Function </TITLE> <SCRIPT LANGUAGE = "JavaScript"> function Sum () { var len = Sum.arguments.length var ans = 0 for (i=0; i<len; i++) { ans += Sum.arguments[i] } document.write( The Sum Is + ans) } </SCRIPT> </HEAD> <BODY> <H1 ALIGN = "CENTER"> Function To Add Two Or More Numbers</H1> <SCRIPT LANGUAGE = "JavaScript"> Sum (10, 20) Sum (10,20,30) Sum (10,20,30,40) </SCRIPT> </BODY> </HTML>

The return Statements <HTML> <HEAD> <TITLE> Sum Function </TITLE> <SCRIPT LANGUAGE = "JavaScript"> function Sum(num1, num2) { var ans = num1 + num2 return ans } </SCRIPT> </HEAD> <BODY> <H1 ALIGN = "CENTER"> Function To Add Two Numbers</H1> <SCRIPT LANGUAGE = "JavaScript"> var total = Sum (1,2) document.write (The Sum Is + total) </SCRIPT> <BODY> </HTML> Java Script Events

When specific action occurs , it generates a signal which is known as event. The code executed in response to an event handler. Fact about an event: It can be triggered by the user It can be triggered by the system It can be triggered by another event

is called an event

Event Handler in Java Script <HTML> <HEAD> <TITLE> JavaScript Events </TITLE> <SCRIPT LANGUAGE = JavaScript> num=0 </SCRIPT></HEAD> <BODY> <A HREF=Hello.html OnMouseOver = ++num; alert(Number : +num)> Place Your Mouse Cursor Over This </A> </BODY></HTML> This event-handler is called when mouseOver events is generated. For event-handler any JavaScript Code, separated by semicolon(;), can be added but statements must be enclosed within single() or double() quotes. Event Handler as a Separate Function <HTML> <HEAD> <TITLE> JavaScript Events </TITLE> <SCRIPT LANGUAGE = JavaScript> num=0 function handler() { num++ alert(Number : + num) } </SCRIPT></HEAD> <BODY> <A HREF=Hello.html OnMouseOver = handler()> Place your mouse cursor over this </A> </BODY></HTML> ex-event2.html

Event Handler returning value <HTML><HEAD> <TITLE> JavaScript Events </TITLE> <SCRIPT LANGUAGE = JavaScript> num=0 function handler() { return confirm(Are You Sure You Want To Visit Astrocity) } </SCRIPT> </HEAD> <BODY> <A Href = www.astrocity.com OnClick = return handler()> Visit AstroCity.Com </A> </BODY></HTML> ex event3.html

The Link Event

Handling mouseOver and mouseOut event <HTML> <HEAD> <TITLE> mouseOver Event </TITLE> <SCRIPT LANGUAGE="JavaScript"> function func(s) { var str = str = "Your have placed the mouse pointer on the alphabet - " str += s alert(str) } function func1()

{ alert("Place mouse cursor over any alphabet") } </SCRIPT> </HEAD> <BODY> <CENTER> <A HREF="" onClick='return false' onMouseOver='func("A")' onMouseOut = func1()>A</A> <A HREF="" onClick='return false' onMouseOver='func("B")' onMouseOut = func1()>B</A> . . . .//same code for all the alphabets . </BODY> </HTML> ex- mouseover.html The Body Event

The Image Event HTML Element HTML Tag Image

JavaScript Description Event Abort

<IMG>

When image loading is cancelled. When there is error while loading an Image. keyDown The user presses a key. keyUp The user releases a key. keyPress The user presses and releases a key. load When an imageis loaded and displayed Error

Event associated with other HTML Tags HTML Element Text field HTML TAG <INPUT TYPE=TEXT> JavaScript Event blur focus change select blur focus

Password field

<INPUT TYPE=PASSWORD>

HTML Element Button

HTML TAG <INPUT TYPE=BUTTON>

JavaScript Event click mousedown mouseup blur focus click blur focus click blur focus

Submit Button

<INPUT TYPE=SUBMIT>

Reset Button

<INPUT TYPE=RESET>

HTML Element Radio Button

HTML TAG <INPUT TYPE=RADIO>

JavaScript Event click blur focus click blur focus

CheckBox

<INPUT TYPE=CHECKBOX>

Selection

<SELECT> </SELECT>

change blur focus

Browser Objects

Java Script object hierarchy is mapped to the DOM, which in turn is mapped to the web page elements in the browser window. Hence, when a web page is rendered in a JavaScript enabled browser window, JavaScript is capable of uniquely identifying each element in the web page, because major elements of a web page are bound to DOM.

Window Object Properties Properties of Window are as follows : closed - Return boolean to determine whether window is closed. defaultstatus - The default message is displayed in status bar.

- Temporary messages that appear in the status bar. frame - array of objects containing all child frame object in a frameset window. location - source location of the document in the window. Properties of Window are as follows : name - The name of the window by which it is identified self - This identifies the current window being referenced. Top - It refers to topmost parent window. parent - It refers to a window which contains another window. Window Object methods alert( message) - Displays an alert dialog box. prompt( message, default_text ) - Displays a prompt dialog box. confirm( message ) - Displays a confirm dialog box. blur() - Removes focus from a window. focus() - Gives focus to a window. close() - Closes the specified window. open(url, window name) - Opens the specified URL in a window specified by the window name.

status

Documents Objcet Properties Proerties of Document Object are as follows Forms[] An array of form objects, one for each <FORM> and </FORM> in the document. The number of forms in the document can be determined using the statement forms.length. Images[] An array of image objects, one for each embedded image. The number of images can be determined using images.length statement. links[] An array of link objects, one for each hypertext link (<A HREF>) in the document. The number of link objects can be determined using links.length statement. Ex formArray.htm window.document.forms[2] or document.form[2] allows to access the content of the third form. window.document.images.length or document.images.length property is used to find out the number of images. For settings of the document following properties are used : linkColor A string that specifies the colour of the unvisited links. alinkColor A string that specifies the colour of a link while it is being activated. vlinkColor A string that specifies the colour of visited links. bgColor A string that specifies the background colour of the document.

fgColor A string that specifies the text colour of the document.

Navigator Object

The navigator object provides browser specific information : version, type , MIME types supported. appVersion version information of the browser. appCodeName the code name of the browser. appName the name of the browser. plugins array of all the plug-ins installed in the browser. mimeTypes array of all mime types currently supported by the browser.

Location Object The following statements display the host name, the protocol name and the pathname of the URL displayed in the window, document.write(File Path : + location.pathname ) document.write(Protocol Used : + location.protocol ) document.write(Host Name : + location.hostname) window.location.href = "http://my.machine.ca/newpage.html" or location.href = http://my.machine.ca/newpage.html

También podría gustarte