Javascript Material

Embed Size (px)

Citation preview

  • 8/14/2019 Javascript Material

    1/47

    JavaScript

    Introduction:

    JavaScript is an interpreted programming language that can be embedded into anHTML web page. Interpreted means that the entire web page is downloaded to thebrowser and the JavaScript code is executed when an event is triggered. When thecode is executed it is interpreted one line at time. There are a number of events thatwill trigger the execution of a JavaScirpt, like a click on a form button, or thecompletion of a web page loading. It is platform specific.

    JavaScript is a scripting language used in many websites. A scripting language is alanguage, which is easy and fast to learn. A scripting language is interpreted in run-time. It is not compiled like other languages as C++, C#, VB.NET etc. JavaScript is aclient side language and it runs on the client browser. JavaScript can be used on all

    most known browsers. However JavaScript can be also used on the server-side. Onthe server side you can use JavaScript for example to manage your database entry.It can be easily used to interact with HTML elements. In other words, JavaScript is alanguage that lets you make your pages interact with your readers and respond towhat they do. It is a programming language that can make your pages feel moredynamic and give feedback to your user. You can validate text fields, disablebuttons, validate forms, or change the background color of your page. All this ispossible with JavaScript. Like each programming language, it contains variables,arrays, functions, operators, objects and much more which can be help you to createbetter scripts for your pages. JavaScript is an object-oriented scripting language thatlets you build interactions between page content, the state of the browser, and the

    actions of the reader. JavaScript code can be inserted directly in the HTML or youcan place it in a separate file with the .js extension and link the web page with the .jsfile.

    The JavaScript language was developed by the Netscape CommunicationsCorporation and is a trademarked name. It is a cross-platform, object-basedscripting language that was originally designed for use in Netscape Navigator.Indeed, versions 2.0, and later, of Navigator can interpret JavaScript statements thatare embedded within HTML code. When a request is made to see a page, the HTMLcode that defines the requested page along with the embedded JavaScriptstatements, are sent by the server to the client. Navigator interprets the HTML

    document and executes the JavaScript code. The resultant page is displayed for theclient. It is important to understand that this interpretation occurs on the client-siderather than the server-side.

    After the success of JavaScript in Navigator 2.0, the Microsoft Corporation was quickto create a clone of JavaScript, called JScript, which is a trademarked name that isdesigned to run inside the Microsoft Internet Explorer. In truth, except for a fewminor differences, JScript is essentially a carbon copy of JavaScript.

  • 8/14/2019 Javascript Material

    2/47

    JavaScript is a simple to comprehend, easy to use, general purpose scriptinglanguage. When used in conjunction with a Web browser's Document Object Model(DOM), it can produce powerful dynamic HTML browser-based applications whichalso can feature animation and sound.

    JavaScript code is placed within the and tags. Script tags canbe put into inside the Header or inside the Body tags. This tells the browser that theflowing bunch of code bounded within and tags is not HTMLto be displayed but rather the code to be processed. One important attribute that isused with tag is type and language. This tells the browser which scriptinglanguage is used.

    Basic format:

    ------------------

    --------------------

    Example:

    document.write = Hello to JavaScript;

    The above example displays the text Hello to JavaScript in the browser.

    JavaScript Vs Java:

    JavaScript Java

    Interpreted (not compiled) by client. Compiled bytecodes downloaded fromserver, executed on client.

    Object-oriented. No distinction between Class-based. Objects are divided into

  • 8/14/2019 Javascript Material

    3/47

    types of objects. Inheritance is throughthe prototype mechanism, and propertiesand methods can be added to any objectdynamically.

    classes and instances with all inheritancethrough the class hierarchy. Classes andinstances cannot have properties ormethods added dynamically.

    Variable data types not declared

    (dynamic typing).

    Variable data types must be declared

    (static typing).Code integrated with, and embedded in,HTML.

    Applets distinct from HTML (accessedfrom HTML pages).

    Core JavaScript

    Client-side and server-side JavaScript have the following elements in common:1. Keywords2. Statement syntax and grammar3. Rules for expressions, variables, and literals4. Underlying object model (although client-side and server-side JavaScript

    have different sets of predefined objects)5. Predefined objects and functions, such as such as Array, Date, and Math

    Client-Side JavaScript:

    When the browser (or client) requests a page, the server sends the full content ofthe document, including HTML and JavaScript statements, over the network. Theclient reads the page from top to bottom, displaying the results of the HTML andexecuting JavaScript statements as it goes. Client-side JavaScript statementsembedded in an HTML page can respond to user events such as mouse clicks. Forexample, you can write a JavaScript function to verify that users enter validinformation into a form requesting a telephone number or zip code. Without anynetwork transmission, the embedded JavaScript on the HTML page can check theentered data and display a dialog box to the user who enters invalid data.

  • 8/14/2019 Javascript Material

    4/47

    Client side JavaScript accommodates the wide range of document object modelsthat are spread among numerous browser brands, operating systems, and versions.

    Server-Side JavaScript:

    JavaScript is also embedded in HTML pages on server-side. The server-sidestatements can connect to relational databases, share information across users ofan application, access the file system on the server, or communicate with other

    applications. JavaScript applications that use server-side JavaScript are compiledinto bytecode executable files. These application executables are run in concert witha web server that contains the JavaScript runtime engine. When a page in theapplication is requested by a client browser, the runtime engine uses the applicationexecutable to look up the source page and dynamically generate the HTML page toreturn. It runs any server-side JavaScript statements found on the page. The resultof those statements might add new HTML or client-side JavaScript statements to the

  • 8/14/2019 Javascript Material

    5/47

    HTML page. It then sends the resulting page over the network to the client, whichdisplays the results

    Server-side JavaScript during development

    Server-side JavaScript during runtime

  • 8/14/2019 Javascript Material

    6/47

    Client Side Vs Server Side JavaScript:

    Client Side JavaScript Server Side JavaScript

    Tags

    Execution Client browser

    (interpreted)

    Server (compiled into SSJS byte code)

    Compilation Not compiled Application file (.web)

    Client JavaScript-enabled Any browser

    Server Any server JavaScript-enabled

    When to Use JavaScript?

    When faced with a Web application task, I look to client-side JavaScript for help withthe following requirements:Data entry validation: If form fields need to be filled out for processing on the

    server, I let client-side scripts prequalify the data entered by the user.Serverless CGIs: I use this term to describe processes that were it not forJavaScript, would be programmed as CGIs on the server, yielding slow performancebecause of the interactivity required between the program and user. This includestasks such as small data collection lookup, modification of images, and generation ofHTML in other frames and windows based on user input.Dynamic HTML interactivity: Its one thing to use DHTMLs capabilities to preciselyposition elements on the pageyou dont need scripting for that. But if you intend tomake the content play on the page, scripting makes that happen.CGI prototyping: Sometimes you may want a CGI program to be at the root of yourapplication because it reduces the potential incompatibilities among browser brands

    and versions. It may be easier to create a prototype of the CGI in client-sideJavaScript.Offloading a busy server: If you have a highly trafficked website, it may bebeneficial to convert frequently used CGI processes to client-side JavaScript scripts.Once a page is downloaded, the server is free to serve other visitors. Not only doesthis lighten server load, but users also experience quicker response to theapplication embedded in the page.Adding life to otherwise dead pages: HTML by itself is pretty flat. Adding ablinking chunk of text doesnt help much; animated GIF images more often distractfrom, rather than contribute to, the user interest at your site. But if you can dream upways to add some interactivity to your page, it may engage the user and encourage

    a recommendation to friends or repeat visits.Creating Web pages that think: You can make your web page think in the waythat they take the decision of their own on execution of some actions.

    Document Object Model

  • 8/14/2019 Javascript Material

    7/47

    To help scripts control various objects/elements, the browser makers define aDocument Object Model (DOM). A model is like a prototype or plan for theorganization of objects on a page. Below fig. shows a map of the lowest commondenominator object model, which is safe to use on all browsers.

    The relationship of all objects with each other is explained below:

    Window object: At the top of the hierarchy is the window. This object represents thecontent area of the browser window where HTML documents appear. In a multiple-frame environment, each frame is also a window (but dont concern yourself with this

    just yet). Because all document action takes place inside the window, it is theoutermost element of the object hierarchy. Its physical borders contain thedocument.

    Document object: Each HTML document that gets loaded into a window becomesa document object. Its position in the object hierarchy is an important one, as youcan see in Figure 4-6. The document object contains most of the other kinds ofobjects in the model. This makes perfect sense when you think about it: The

    document contains the content that you are likely to script. The biggest improvementis that every HTML element becomes an object that scripts can manipulate.Form object: Users dont see the beginning and ending of forms on a page, onlytheir elements. But a form is a distinct grouping of content inside an HTMLdocument. Everything that is inside the ... tag set is part of theform object. A document might have more than one pair of tags if dictatedby the page design.

  • 8/14/2019 Javascript Material

    8/47

    Form control elements: Just as your HTML defines form elements within theconfines of the ... tag pair, so does a form object contain all theelements defined for that object. Each one of those form elementstext fields,buttons, radio buttons, checkboxes, and the likeis a separate object.

    Comments

    Text which is commented is ignored by the interpreter from that point to the end ofthe line. There are two types of comments: those that run to the end of the currentline and those that span multiple lines. Single-line comments begin with a doubleforward slash (//). For example:

    var count = 10; // holds number of items the user wishes to purchase

    Comments spanning multiple lines are enclosed between a slash-asterisk (/*) andasterisk-slash (*/) pair. For example:

    /*var count = 10;var y = square(10);*/

    Conventions

    JavaScript is case-sensitive.

    At the end of every JavaScript statement, semicolon is required whichindicates the end of statement. For eg:

    var x = 0;

    The double quotation mark can be found within strings that start, and end with(are delimited by) single quotes (He said, JavaScript is an interesting language.)

    The single quotation mark can be used within a string delimited by doublequotation marks.

    JavaScript ignores spaces, tabs, and newlines that appear in statements.However it recognizes spaces, tabs, and tabs that are part of string. For eg:

    var x=0; is same as var x = 0;

    The backslash (\) is followed by another character that represents somethingin a string that cannot be typed on keyboard. The \ tells the interpreter that in thiscase it should print the character and not interpret as a delimiter. For eg:

    You\nPressed\nEnter key

    \n represents carriage return and a line feed. The result of above eg. is :

  • 8/14/2019 Javascript Material

    9/47

    YouPressedEnter key

    These backslashes and letter combination is known as Escape Sequences.

    Some common of them are listed below:\b backspace\f form feed\n new line\r carriage return (no line feed)\t tab\ single quote\ double quotes

    Data Types

    Various data types in JavaScript are as follows:1. Numerical Data: This consists of numbers both integer and floating. Forexample 17, 21.5 etc2. Text: Also called String. This consists of text specified within single or doublequotes. For example Hello, World etc3. Boolean: This consists of Boolean value i.e. true or false.

    Declaring and Initializing Variables

    A variable can be declared by using varkeyword. For examplevar sum;

    A variable can be assigned value as:var name = Hello;

    Every JavaScript variable has a data type, but the type is inferred from the variablescontent. For example, a variable that is assigned a string value assumes the stringdata type. A consequence of JavaScripts automatic type inference is that avariables type can change during script execution. For example, a variable can holda string at one point and then later be assigned a Boolean. Its type changesaccording to the data it holds. There is no need to indicate type in variabledeclarations.

    To check the type of variable, typeofoperator is used. For eg:var x = 5;alert (typeof x);

    The output is string. alert() function is used to display text in message box. It will beexplained later..

  • 8/14/2019 Javascript Material

    10/47

    Data Type Conversion

    JavaScript tries its best to perform internal conversions to solve data typeconversion, but JavaScript cannot read your mind. If your intentions differ from theway JavaScript treats the values, you wont get the results you expect.

    A case in point is adding numbers that may be in the form of text strings. In a simplearithmetic statement that adds two numbers together, you get the expected result:

    3 + 3 // result = 6

    But if one of those numbers is a string, JavaScript leans toward converting the othervalue to a stringthus turning the plus signs action from arithmetic addition to

    joining strings. Therefore, in the statement3 + 3 // result = 33

    the string-ness of the second value prevails over the entire operation. The firstvalue is automatically converted to a string, and the result joins the two strings.

    Look what happens when another number is added to the statement:3 + 3 + 3 // result = 63

    This might seem totally illogical, but there is logic behind this result. The expressionis evaluated from left to right. The first plus operation works on two numbers,yielding a value of 6. But as the 6 is about to be added to the 3, JavaScript lets thestring-ness of the 3 rule. The 6 is converted to a string, and two string values are

    joined to yield 63.

    Operators

    Lots of operators are used in various expressions. Various categories are described

    below:Assignment Operator: the most basic operator is the assignment operator (=),which is used to assign a value to a variable. Often this operator is used to set avariable to a value. For eg:

    var str = Hello;

    Generally, the assignment operator is used to assign a value to a single variable, butit is possible to perform multiple assignments at once by stringing them together withthe = operator. For eg:

    var x = y = z = 7;

    Assignments can also be used to set a variable to hold the value of an expression.For eg:

    var x = 12 + 5;

    Arithmetic Operators: JavaScript supports all the basic arithmetic operators likeaddition (+), subtraction (), multiplication (*), division (/), and modulus (%, alsoknown as the remainder operator). For eg:

    var x = 10 + 5;

  • 8/14/2019 Javascript Material

    11/47

    Comparison Operators: these operators compare values in scriptswhether twovalues are the same. These kinds of comparisons return a value of the Boolean typetrue or false. The operator that tests whether two items are equal consists of a pairof equal signs to distinguish it from the single equal sign assignment operator. Other

    comparison operators are listed below:== Equals! Not!= Does not equal> Is greater than>= Is greater than or equal to< Is less than>> Unsigned Shift Right& bitwise AND^ bitwise XOR| bitwise OR

  • 8/14/2019 Javascript Material

    12/47

  • 8/14/2019 Javascript Material

    13/47

    to a function, the this operator stands in for the current object reference andappends the proper syntax to reference the value property:

    this operator also works inside other objects, such as custom objects. When youdefine a constructor function for a custom object, using this operator to define

    properties of the object and assign values to those properties is common practice.Consider the following example of an object creation sequence:function bottledWater(brand, size, flavor){

    this.brand = brandthis.size = sizethis.flavor = flavor

    }var myWater = new bottledWater(Crystal Springs, 16, original)

    Control Structures

    The kinds of statements that make decisions and loop around to repeat themselvesare called control structures. A control structure directs the execution flow through asequence of script statements based on simple decisions and other factors. Animportant part of a control structure is the condition. A program sometimes have tobranch to an execution route if a certain condition exists. Each condition is anexpression that evaluates to true or false. JavaScript provides several kinds ofcontrol structures for different programming situations. Three of the most commoncontrol structures youll use are if constructions, if...else constructions, and for loops.

    If Structure

    if statement is JavaScripts basic decision-making control statement. It allows yourprogram to perform a test and act based on the results of the test. The syntax is:

    if (condition){

    statement[s] if true}

    For eg:var x = 5;if (x >> 1){

    alert("x is greater than 1");}alert("moving on ...");

    The expression evaluates to true, displays the message x is greater than 1, andthen displays the second alert dialog afterward. However, if the value of variable xwere something like zero, the expression would evaluate false, resulting in skippingthe first alert and immediately displaying the second one.

  • 8/14/2019 Javascript Material

    14/47

    if . . . else structure

    In the plain if construction, no special processing is performed when the conditionevaluates to false. But if processing must follow one of two special paths, you need

    the if...else structure. The syntax is as follows:if (condition){

    statement[s] if true}else{

    statement [s] if false}

    For eg:if (sum ==0)

    { sum = x +y;}else{

    subtotal =sum ;}

    If sum equals to 0 then sum equals x plus y, or else subtotal equals sum.

    ifelse if structure

    More advance than if..else is ifelse if construct. You can evaluate your more thanmore one conditions and can process it. The syntax is as follows:

    if (expression1)statement or block

    else if (expression2)statement or block

    else if (expression3)statement or block

    ...else

    statement or blockFor eg:

    If (x>5){

    alert (x is greater than 5);}else if (x

  • 8/14/2019 Javascript Material

    15/47

    alert (x is less than 10);}else{

    alert (unknown);

    }

    The above code checks for the value of x. if it is greater than 5, 1 st block is executed.If it is less than 10, 2nd block is executed. If both the conditions are false, last block isexecuted.

    switchThe switch statement is used when a variable may take a number of values and youwant to test for some of those values. The basic syntax of the switch statement is togive an expression to evaluate and several different statements to execute based onthe value of the expression. The interpreter checks each case against the value of

    the expression until a match is found. If nothing matches, a default condition will beused. The syntax is as follows:switch (expression){

    case condition 1: statement(s)break;

    case condition 2: statement(s)break;

    ...case condition n: statement(s)

    break;

    default: statement(s)}The breakstatement indicates the end of that particular case. If they were omitted,the interpreter would continue executing each statement. For eg:

    var yourGrade='A';switch (yourGrade){

    case 'A': alert("Good job.");break;

    case 'B': alert("Pretty good.");break;

    case 'C': alert("You passed!");break;

    case 'D': alert("Not so good.");break;

    case 'F': alert("Back to the books.");break;

    default: alert("Grade Error!");}

  • 8/14/2019 Javascript Material

    16/47

    continue

    The continue statement tells the interpreter to immediately start the next iteration ofthe loop. When its encountered, program flow will move to the loop check

    expression. The below example shows how the continue statement is used to skipprinting when the index held in variable x reaches 8:var x = 0;while (x

  • 8/14/2019 Javascript Material

    17/47

    document.write(count+"
    ");count++;

    }document.write("Loop done!");

    for

    for loops are useful when you know exactly how many times you want the loop toexecute. The initialization statement is executed before the loop begins, the loopcontinues executing until test condition becomes false, and at each iteration theiteration statement is executed. The syntax is as follows:

    for (initialization; test condition; iteration statement){

    loop statement or block}

    For eg:

    for (var i = 0; i < 10; i++)document.write ("Loop " + i + "
    ");

    It prints the numbers zero through nine.

    Functions

    Functions allow you to create bunch of code that perform specific task. JavaScripthas a number of built-in functions that are part of the language. It also allows theuser to create its own functions. A function is capable of returning a value to thestatement that invoked it, but this is not a mandatory. The function can return thevalue using return keyword. When a function returns a value, the calling statement

    treats the function call like any expressionplugging in the returned value rightwhere the function call is made. Function can return only one value. The syntax is asfollows:

    function functionName ( [parameter1]...[,parameterN] ){

    statement[s]}

    A simple function that takes no parameters called sayHello is defined below:function sayHello(){

    alert("Hello there");

    }To invoke the function somewhere later in the script, you have to write the statementsomething like this:

    sayHello();You also can define functions so they receive parameter values from the callingstatement. Below eg. shows a simple document that has a button whose onClickevent calls a function while passing text data to the function.

  • 8/14/2019 Javascript Material

    18/47

    function showMsg(msg){

    alert(The button sent: + msg)

    }

    When a function receives parameters, it assigns the incoming values to the variablenames specified in the function definitions parentheses. Consider the followingscript segment:

    function sayHiToFirst(p, q, r){

    alert(Say hello, + a)}sayHiToFirst(A, B, C)sayHiToFirst(X, Y, Z)

    After the function is defined in the script, the next statement calls that function,passing three strings as parameters. The function definition automatically assigns

    the strings to variables p, q, and r. Therefore, before the alert() statement inside thefunction ever runs, p evaluates to A, q evaluates to B, and r evaluates to C. Inthe alert() statement, only the p value is used and the alert reads

    Say hello, AWhen the user closes the first alert, the next call to the function occurs. This timethrough, different values are passed to the function and assigned to p, q, and r. Thealert dialog box reads

    Say hello, D

    Returning values from function is demonstrated as below:function addThree(arg1, arg2, arg3){

    return (arg1+arg2+arg3);}var x = 5, y = 7, result;

    result = addThree(x,y,11);alert(result);

    Variable Scope

  • 8/14/2019 Javascript Material

    19/47

    There are only two basic scopes: global and local. Variables defined outside offunctions are called global variables. They are known (visible) throughout adocument. Variables defined inside functions are called local variables.It is limited tothe particular block of code it is defined within. The body of a function has its own

    local scope. Local scope allows for the reuse of variable names within a document.For eg:

    var aBoy = John // globalvar hisDog = Snoopy // globalfunction demo(){

    // using improper design to demonstrate a pointvar hisDog = Tommy // local version of hisDog

    var output = hisDog + does not belong to +aBoy + .
    document.write(output)

    }

    demo() // runs as document loadsdocument.write(hisDog + belongs to + aBoy + .)

    When the page loads, the script in the Head portion initializes the two globalvariables (aBoy and hisDog) and defines the demo() function in memory. In theBody, another script begins by invoking the function. Inside the function, a localvariable is initialized with the same name as one of the global variableshisDog. InJavaScript, such a local initialization overrides the global variable for all statementsinside the function. (But note that if the var keyword is left off of the localinitialization, the statement reassigns the value of the global version to Tommy.)Another local variable, output, is used to store text which is to be written on thescreen. The accumulation begins by evaluating the local version of the hisDog

    variable. Then it concatenates some hard text. Next comes the evaluated value ofthe aBoy global variableany global not overridden by a local is available for useinside the function. The expression is accumulating HTML to be written to the page,so it ends with a period and a
    tag. The final statement of the function writesthe content to the page. After the function completes its task, the next statement inthe Body script writes another string to the page. Because this script statement isexecuting in global space, it accesses only global variables including those

  • 8/14/2019 Javascript Material

    20/47

    defined in another tag set in the document. By the time the completepage finishes loading, it contains the following text lines:

    Tommy does not belong to John.Snoopy belongs to John.

    What are Events?

    Events are signals generated when specific actions occur. Scripts can be built toreact to these events. Various events available in JavaScript are as follows:

    1. Abort:This event is occurs when the user cancels loading of an image.

    2. Blur:This event occurs when input focus is removed from a form element or focus isremoved from a window.

    3. Click:This event occurs when the user clicks on a link or form element.

    4. Double Click:This event occurs when the user double clicks on a link or form element.

    5. Change:This event occurs when the value of a form field is changed by the user.

    6. Drag Drop:This event occurs when an icon is dragged and dropped into the browser.

    7. Error:This event occurs when an error occurs during loading of document or image.

    8. Focus:This event occurs when input focus is given to a form element or a window byclicking on it or by pressing TAB key.

    9. Load:

    This event occurs when a page is loaded in the browser.

    10. Mouse Down:This event occurs when the user presses a mouse button.

    11. Mouse Move:This event occurs when the user moves the mouse.

  • 8/14/2019 Javascript Material

    21/47

    12. Mouse Out:This event occurs when the user moves the pointer off of a link or clickable area ofan imagemap.

    13.Mouse Over:This event occurs when the user moves the pointer over a hypertext link.

    14. Mouse Up:This event occurs when the user releases a mouse button.

    15. Key Down:This event occurs when the user presses any key.

    16. Key Press:This event occurs when the user presses or holds down a key.

    17. Key Up:This event occurs when the user releases a key.

    18. Move:This event occurs when the user moves the browser window or frame.

    19. Resize:This event occurs when the user resizes the browser window or frame.

    20.

    Reset:This event occurs when the user clears a form using the reset button.

    21. Select:This event occurs when the user selects text within the field.

    22. Submit:This event occurs when a form is submitted.

    23. Unload:This event occurs when the user leaves the page.

    What are Event Handlers?

    Event handlers are small JavaScript code placed inside an HTML tag. EventHandlers are scripts in the form of attributes of specific HTML tags. They help inhandling (catching) events. The basic format of an event handler is:

  • 8/14/2019 Javascript Material

    22/47

    Any JavaScript statements or functions can appear within the quotation marks of anevent handler. For example, if you have a form with a text field and want to call thefunction checkField() whenever the value of text field changes, you should define as:

    Various event handlers are as follows:onAbort onKeyDownonBlur onKeyPressonClick onKeyUponDblClick onMoveonChange onResizeonDragDrop onResetonError onSelectonFocus onSubmit

    onLoad onUnloadonMouseDownonMouseMoveonMouseOutonMouseOveronMouseUp

    Below table shows which window and form elements have event handlers availableto them:

    Sr.

    No.

    Object Event Handlers Available

    1 Selection List onBlur, OnChange, OnFocus

    2 Text onBlur, OnChange, OnFocus, onSelect

    3 Textarea onBlur, OnChange, OnFocus, onSelect, onKeyDown,onKeyPress

    4 Button onClick, onBlur, onFocus, onMouseDown, onMouseUp

    5 Checkbox onClick, onBlur, onFocus

    6 Radio Button onClick, onBlur, onFocus

    7 Hypertext Link onClick, onMouseOver, onMouseOut, onKeyDown,onKeyPress, onMouseDown, onMouseOut, onMouseOver,onMouseUp

    8 ClickableImage Area

    onMouseOver, onMouseOut

    9 Reset onClick, onBlur, onFocus

    10 Submit onClick, onBlur, onFocus

    11 Document onLoad, onUnload, onError, onClick, onDblClick,onKeyDown, onKeyPress, onMouseDown, onMouseUp

    12 Window onLoad, onUnload, onBlur, onFocus, onDragDrop, onError,

  • 8/14/2019 Javascript Material

    23/47

  • 8/14/2019 Javascript Material

    24/47

    var myArray = new Array();

    myArray[0] = Bob;myArray[1] = Peter;myArray[2] = Paul;

    document.write (myArray[0] = + myArray[0] +
    );document.write (myArray[1] = + myArray[1] +
    );document.write (myArray[2] = + myArray[2] +
    );

    myArray[1] = Changed;document.write (myArray[1] changed to = + myArray[1]+
    );

    Although not explicitly included in the language, most JavaScript implementationssupport a form of multidimensional arrays. A multidimensional array is an array thathas arrays as its elements.

    Example:

    Multi Dimension Array

    var personnel = new Array();

    personnel[0] = new Array();personnel[0][0] = Name0;personnel[0][1] = Age0;personnel[0][2] = Address0;

    personnel[1] = new Array();personnel[1][0] = Name1;personnel[1][1] = Age1;personnel[1][2] = Address1;

    personnel[2] = new Array();personnel[2][0] = Name2;personnel[2][1] = Age2;personnel[2][2] = Address2;

    document.write(Name: + personnel[1][0] +
    );

  • 8/14/2019 Javascript Material

    25/47

    document.write(Age: + personnel[1][1] +
    );document.write(Address: + personnel[1][2] +
    );

    The length property retrieves the index of the next available (unfilled) position at theend of the array. Even if some lower indices are unused, length gives the index ofthe first available slot after the last element. Consider the following:

    var myArray = new Array();myArray[1000] = "This is the only element in the array";alert(myArray.length);

    Even though myArray only has one element at index 1000, as we see by the alertdialog myArray.length, the next available slot is at the end of the array, 1001. Thelength property is automatically updated as new elements are added to the array.

    Setting length to a value greater than the index of the last valid element has noeffect on the array contents, though it will increase the number of undefined slots inthe array. Consider, for example, the result of the following script,

    var myArray = ["red", "green", "blue"];myArray.length = 20;alert("myArray="+myArray);

    the output is:

    Array has various methods. They are described as follows:1. push(), pop(), shift(), unshift():push() method appends the element to the end of the array and increases thelength property accordingly. pop() method removes the array element from endand decreases the length property accordingly. For eg:

    var stack = [ ]; // [ ]

    stack.push("first"); // ["first"]stack.push(10, 20); // ["first", 10, 20]stack.pop(); // ["first", 10] Returns 20stack.push(2); // ["first", 10, 2]stack.pop(); // ["first", 10] Returns 2stack.pop(); // ["first"] Returns 10stack.pop(); // [ ] Returns "first"

  • 8/14/2019 Javascript Material

    26/47

    unshift() and shift() methods work same as push() and pop(), except that they addand remove data from the front of the array. Invoking unshift() inserts its arguments(in order) at the beginning of the array, shifts existing elements to higher indices, andincrements the arrays length property accordingly. For example,

    var myArray = [345, 78, 2];

    myArray.unshift(4,"fun");alert(myArray);adds two more elements to the front of the array, as shown below:

    2. concat():The concat() method returns the array resulting from appending its arguments to thearray on which it was invoked. For eg:

    var myArray = ["red", "green", "blue"];alert(myArray.concat("cyan", "yellow"));

    the output is shown here:

    3. join():The join() method converts the array to a string and allows the programmer tospecify how the elements are separated in the resulting string. When you print anarray, the output is a comma-separated list of the array elements. You can use join()to format the list separators as you like. Fro eg:

    var myArray = ["red", "green", "blue"];var stringVersion = myArray.join(" / ");alert(stringVersion);

  • 8/14/2019 Javascript Material

    27/47

    4. reverse():

    Objects

    1. Document

    The Documentobject provides access to the elements in an HTML page from withinyour script. This includes the properties of every form, link and anchor (and, whereapplicable, any sub-elements), as well as global Document properties such asbackground and foreground colors.

    Example:

    Document Object Example

    function documentPropertiesMethods(form){

    document.alinkColor = "Red";//document.linkColor = "Green";document.vlinkColor = "Blue";//alert("links" + " " + document.Links);alert("anchors" + " " + document.anchors.length);document.bgColor = "00ffff";//document.fgColor = "Red";alert("forms" + " " + document.forms.length);

    alert("images" + " " + document.images.length);alert("lastmodified" + " " + document.lastModified);alert("title" + " " + document.title);

    var myPage = "all HTML coding here";document.open();document.write(myPage);document.writeln("2nd time");document.close();

    }

    HelloWorld1World2

  • 8/14/2019 Javascript Material

    28/47

    Properties

    alinkColor:

    Syntax: document.alinkColor = "colorinfo"

    This property defines the color of an active link. The "color info" argument is a stringthat can contain either the hexadecimal definition of the color or its literal description.If you use the hex definition of a color it must be in the format rrggbb - for example,

    the hex value for the named color 'forest green' is '228B22'.

    anchors:

    This property is an array containing references to all the named Anchor objects inthe current document. These references are stored in the array in the order in whichthey are defined in the source code. The "anchorID" argument is used to accessitems in the array and this can either be a string containing the anchor name asdefined within the tags in the HTML source, or an integer (with '0' being thefirst item in the array).

    Both examples below return the same results; the first uses the defined names ofthe anchors and the second uses their reference number within the array.

    applets:

    Syntax: document.applets["appletID"]

    This property is an array containing references to all the Applet objects in the currentdocument. These references are stored in the array in the order in which they aredefined in the source code. The "appletID" argument is used to access items in thearray and this can either be a string containing the applet name as defined within the tags in the HTML source, or an integer (with '0' being the first item in thearray).

    bgColor:

    Syntax: document.bgColor = "colorinfo"

    http://www.devguru.com/technologies/javascript/10630.asphttp://www.devguru.com/technologies/javascript/10631.asphttp://www.devguru.com/technologies/javascript/10632.asphttp://www.devguru.com/technologies/javascript/10633.asphttp://www.devguru.com/technologies/javascript/10631.asphttp://www.devguru.com/technologies/javascript/10632.asphttp://www.devguru.com/technologies/javascript/10633.asphttp://www.devguru.com/technologies/javascript/10630.asp
  • 8/14/2019 Javascript Material

    29/47

    This property defines a document's background color. The "colorinfo" argument is astring that can contain either the hexadecimal definition of the color or its literaldescription. If you use the hex definition of a color it must be in the format rrggbb -for example, the hex value for the named color 'forest green' is '228B22'.

    fgColor:

    Syntax: document.fgColor = "colorinfo"

    This property defines a document's foreground (text) color. The "colorinfo" argumentis a string that can contain either the hexadecimal definition of the color or it's literaldescription. If you use the hex definition of a color it must be in the format rrggbb -for example, the hex value for the named color 'forest green' is '228B22'.

    formName:

    Syntax: document.formname

    Every form in a document has a separate document object property, the name ofwhich is taken from the value assigned to the form with the tag. Any form in the document can then be referred to with the syntaxbelow.

    forms:

    Syntax: document.forms["formID" ]

    This property is an array containing references to all the Form objects in the currentdocument. These references are stored in the array in the order in which they aredefined in the source code. The "formID" argument is used to access items in thearray and this can either be a string containing the form name as defined within the tag in the HTML source, or an integer (with '0' being the first item in thearray).

    images:

    Syntax: document.images["imageID"]

    This property is an array containing references to all the Image objects in the currentdocument. These references are stored in the array in the order in which they are

    http://www.devguru.com/technologies/javascript/10637.asphttp://www.devguru.com/technologies/javascript/10638.asphttp://www.devguru.com/technologies/javascript/10639.asphttp://www.devguru.com/technologies/javascript/10640.asphttp://www.devguru.com/technologies/javascript/10637.asphttp://www.devguru.com/technologies/javascript/10638.asphttp://www.devguru.com/technologies/javascript/10639.asphttp://www.devguru.com/technologies/javascript/10640.asp
  • 8/14/2019 Javascript Material

    30/47

    defined in the source code. The "imageID" argument is used to access items in thearray and this can either be a string containing the image name as defined within the tag in the HTML source, or an integer (with '0' being the first item in thearray).

    lastModified:

    Syntax: document.lastModified

    This property returns the date that the document was last modified. This propertyreturns a string relating to the date that the document was last modified, which isusually, but not always, contained in the HTTP header of a document. When thisdata is supplied, the server from which the document originated interrogates the filefor its 'last modified' date and includes this in the header information of thedocument. If a particular server doesn't do this, and no 'date last modified' dataexists in the HTTP header, JavaScript will return a value of '0', which it interprets as

    'January 1, 1970 GMT'

    linkColor:

    Syntax: document.linkColor = "colorinfo"

    This property defines the color of any hyperlinks in the document. The "colorinfo"argument is a string that can contain either the hexadecimal definition of the color orit's literal description. If you use the hex definition of a color it must be in the formatrrggbb - for example, the hex value for the named color 'forest green' is '228B22'.

    links:

    Syntax: document.links["linkID"]

    This property is an array containing references to all the Area and Link objects in thecurrent document. These references are stored in the array in the order in whichthey are defined in the source code. The "linkID" argument is an integer relating to alink defined within a or tag in the HTML source.

    title:

    Syntax: document.title

    This property returns the document's name as defined between the tags.

    http://www.devguru.com/technologies/javascript/10641.asphttp://www.devguru.com/technologies/javascript/10643.asphttp://www.devguru.com/technologies/javascript/10644.asphttp://www.devguru.com/technologies/javascript/10647.asphttp://www.devguru.com/technologies/javascript/10641.asphttp://www.devguru.com/technologies/javascript/10643.asphttp://www.devguru.com/technologies/javascript/10644.asphttp://www.devguru.com/technologies/javascript/10647.asp
  • 8/14/2019 Javascript Material

    31/47

    url:

    Syntax: document.URL

    This property is used to retrieve the document's full URL.

    vlinkColor:

    Syntax: document.vlinkColor = "colorinfo"

    This property defines the color of any visited links in the document. The "colorinfo"argument is a string that can contain either the hexadecimal definition of thecolor or its literal description. If you use the hex definition of a color it must bein the format rrggbb - for example, the hex value for the named color 'forestgreen' is '228B22'.

    Methods

    close:

    Syntax: document.close( )

    This method closes an output stream previously opened with the document.openmethod and forces data collected from any instances of the document.write ordocument.writeln methods to be displayed.

    Example:

    function newWindowTest()

    {var message1 = "Hello, world!"var message2 = "This is a test."newWindow.document.open("text/html", "replace")newWindow.document.writeln("message1)newWindow.document.write("message2)newWindow.document.close()

    }

    newWindow=window.open('','','toolbar=no,scrollbars=no,width=200,height=150'

    )newWindowTest()

    Output:

    "Hello, world! This is a test."

    This example demonstrates this and displays the output stream in a new window.

    http://www.devguru.com/technologies/javascript/10649.asphttp://www.devguru.com/technologies/javascript/10651.asphttp://www.devguru.com/technologies/javascript/10649.asphttp://www.devguru.com/technologies/javascript/10651.asp
  • 8/14/2019 Javascript Material

    32/47

    getElementById:

    Syntax: document.getElementById(id)

    This element receives a string containing the id of a specific element and returns areference to it. After obtaining a reference to the object, you can use thegetAttribute and setAttribute methods to modify the element's attributes.

    Example:

    ...var pTag1 = document.getElementById('myID');document.write(pTag1.getAttribute('attr') + '
    \n');pTag1.setAttribute('attr', 'my new attribute value');document.write(pTag1.getAttribute('attr'));

    Output:

    my attribute valuemy new attribute value

    open:

    Syntax: document.open([mimeType[, replace]])

    This method is used to open a stream to collect the output from any write or writelnmethods. The first of the optional parameters is mime Type which determinesthe type of document you are writing to; if this parameter is not used, thedefault value is "text/html". The second parameter is replace, also optional,which causes the history entry for the new document to inherit the history entryfrom the document from which it was opened.

    Example:

    function newWindowTest()

    {

    var message1 = "Hello, world!"var message2 = "This is a test."newWindow.document.open("text/html", "replace")newWindow.document.writeln(message1)newWindow.document.write(message2)newWindow.document.close()

    }

    http://www.devguru.com/technologies/javascript/17445.asphttp://www.devguru.com/technologies/javascript/10654.asphttp://www.devguru.com/technologies/javascript/17445.asphttp://www.devguru.com/technologies/javascript/10654.asp
  • 8/14/2019 Javascript Material

    33/47

    newWindow=window.open('','','toolbar=no,scrollbars=no,width=200,height=150')newWindowTest()

    Output:

    "Hello, world! This is a test."

    The following code demonstrates this method and displays the output stream in anew window.

    write:

    Syntax: document.write("expression1", [expression2, [...]])

    This method is used to write HTML expressions to the specified document in acurrent or new window. Multiple arguments, ("expression1", [expression2,

    [...]]), can be listed and they will be appended to the document in order ofoccurrence. They can be of any type supported by JavaScript (string, numeric,logical), but all non-string expressions will be converted to a string before beingappended.

    In general, it is not necessary to open the document using the document.openmethod; since the document.write method will automatically open the file anddiscard (erase) the contents. However, after the write is complete, you need toclose the document by using the document.close method. In some browsers,the results of the write may not be completely displayed, due to buffering, untilthe close occurs.

    Example:

    newWindow = window.open('', 'newWin')var tagBoldOpen = ""var tagBoldClose = ""newWindow.document.write(tagBoldOpen)newWindow.document.write("This is some bold text.", tagBoldClose)newWindow.document.close()

    writeln:

    Syntax: document.writeln("expression(s)")

    This method is identical to the write method detailed above, with the addition ofwriting a new line character after any specified expressions.

    Form:

    http://www.devguru.com/technologies/javascript/10657.asphttp://www.devguru.com/technologies/javascript/10658.asphttp://www.devguru.com/technologies/javascript/10657.asphttp://www.devguru.com/technologies/javascript/10658.asp
  • 8/14/2019 Javascript Material

    34/47

    Forms allow us to prompt a user for input using elements such as radio buttons,checkboxes and selection lists. Data gathered in this manner can then beposted to a server for processing. A form is created by enclosing HTMLcontrols and other elements within tags. A page can contain asmany forms as required, but they cannot be overlapping or nested (the closing

    tag of a form must precede the opening tag of any subsequent form).

    Example:

    Form Object Example

    Enter your name:

    Favorite Ice Cream Flavor:

    ChocolateStrawberryVanilla

    alert(form1.length);

    Properties

    action:

    Syntax: object.action = URL

    This property specifies the URL address to which the data gathered by the form willbe submitted. An email address can also be specified using the'mailto:[email protected]' syntax.

    elements:

    http://www.devguru.com/technologies/javascript/10681.asphttp://www.devguru.com/technologies/javascript/10682.asphttp://www.devguru.com/technologies/javascript/10681.asphttp://www.devguru.com/technologies/javascript/10682.asp
  • 8/14/2019 Javascript Material

    35/47

  • 8/14/2019 Javascript Material

    36/47

    reset:

    Syntax: object.reset( )

    This method resets the default values of any elements in a form. Emulates theclicking of a Reset button (although it is not necessary to have a reset button ina form to use this method).

    submit:

    Syntax: object.submit( )

    This method submits a Form. This is the same as clicking a Submit button.

    History:

    The History object is a predefined JavaScript object which is accessible through the

    history property of a window object.

    The window.history property is an array of URL strings which reflect the entries inthe History object. The History object consists of an array of URLs, accessiblethrough the browser's Go menu, which the client has visited within a window. Itis possible to change a window's current URL without an entry being made inthe History object by using the location.replace method.

    Example:

    1.

    function doIt(){

    var _p1 ='"historyWindow","width=500,height=300,menubar,resizable"';var w=window.open("",_p1);var d=w.document;

    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");for(var i=0;i

  • 8/14/2019 Javascript Material

    37/47

    d.close();return w;

    }doIt()


    JS-Examples.com

    2.

    History Object Example

    function historyPropertiesMethods(form){alert(history.current);alert(history.length);alert(history.next);alert(history.previous);

    alert(history.back());alert(history.forward());alert(history.go(1));

    }

    Properties

    current:

    Syntax: history.current

    The current property contains the complete URL of the current History entry.

    length:

    http://www.devguru.com/technologies/javascript/10947.asphttp://www.devguru.com/technologies/javascript/10948.asphttp://www.devguru.com/technologies/javascript/10947.asphttp://www.devguru.com/technologies/javascript/10948.asp
  • 8/14/2019 Javascript Material

    38/47

    Syntax: history.length

    The length property contains the number of elements in the History list.

    next:

    Syntax: history.next

    The next property contains the complete URL of the next element in the History list,and is the equivalent of the URL the user would go to if they selected Forwardin the Go menu.

    previous:

    Syntax: history.previous

    The previous property contains the complete URL of the previous element in the

    History list, and is the equivalent of the URL the user would go to if theyselected Back in the Go menu.

    Methods

    back:

    Syntax: history.back()

    The back method loads the previous URL in the History list, and is equivalent to thebrowser's Back button and to history.go(-1).

    forward:

    Syntax: history.forward()

    The forward method loads the next URL in the History list, and is equivalent to thebrowser's Forward button and to history.go(1).

    go:

    Syntax: history.go(delta)

    history.go(location)

    The go method loads a specified URL from the History list.

    Image:

    http://www.devguru.com/technologies/javascript/10949.asphttp://www.devguru.com/technologies/javascript/10950.asphttp://www.devguru.com/technologies/javascript/10951.asphttp://www.devguru.com/technologies/javascript/10952.asphttp://www.devguru.com/technologies/javascript/10953.asphttp://www.devguru.com/technologies/javascript/10949.asphttp://www.devguru.com/technologies/javascript/10950.asphttp://www.devguru.com/technologies/javascript/10951.asphttp://www.devguru.com/technologies/javascript/10952.asphttp://www.devguru.com/technologies/javascript/10953.asp
  • 8/14/2019 Javascript Material

    39/47

    Syntax: new Image([width,] [height])

    The Image object is an image on an HTML form, created by using the HTML 'IMG'tag. Any images created in a document are then stored in an array in thedocument.images property, and it is from here that they are accessed. If you

    have specified a name for an image created using the HTML 'IMG' tag, you canuse that name when you index the image in the images array. You can alsouse the Image constructor and the new operator to create an image objectwhich can then be displayed within an existing cell. The main use of this is toload an image from the network so that it is in cache before it needs to bedisplayed.

    When one Image object replaces another, it cannot change the width andheight properties of it (these are read-only for this object) and the browserdisplays the image with the dimensions set in the IMG tag. JavaScript can alsobe used to create animation by repeatedly changing the value of the srcproperty.

    This isn't as fast as GIF animation because Javascript has to load each individualframe as a separate file, whereas with GIF animation all the frames arecontained in one file.

    NOTE: The event handlers onClick, onMouseOut and onMouseOver can alsobe used with the Internet Explorer browser, but not with Netscape. You can,however, use these event handlers in conjunction with the Image object withNetscape, if you define an Area object for the image, or if the IMG tag is placedwithin a Link object.

    Examples:

    History Object Example

    function imagePropertiesMethods(form){

    }

  • 8/14/2019 Javascript Material

    40/47

    myImage = new Image()myImage.src = "C:/Personal/Mountain.gif"

    The above two lines will create an Image object called MyImage.

    Properties

    border:

    Syntax: Image.border

    The border property is read-only, and is a string stating the width of the border of animage in pixels. For an image created using the Image constructor, this is 0.

    complete:

    Syntax: Image.complete

    The complete property is read-only and returns a Boolean value indicating whetheror not the browser has completed loading the image.

    constructor:

    Syntax: Object.constructor

    This specifies a function to create an object's property and is inherited by all objects

    from their prototype.

    height:

    Syntax: Image.height

    The height property is read-only, and is a string stating the HEIGHT attribute of anIMG tag in pixels. Where an image has been created using the Imageconstructor, the height is of the image itself, not the HEIGHT value of thedisplay.

    hspace:

    Syntax: Image.hspace

    The hspace property is read-only and specifies the HSPACE value of the IMG tag,which is the number of pixels space between the left and right margins of animage and surrounding text. For an image created using the Image constructor,the value of this property is null.

    http://www.devguru.com/technologies/javascript/11136.asphttp://www.devguru.com/technologies/javascript/11137.asphttp://www.devguru.com/technologies/javascript/10763.asphttp://www.devguru.com/technologies/javascript/11138.asphttp://www.devguru.com/technologies/javascript/11139.asphttp://www.devguru.com/technologies/javascript/11136.asphttp://www.devguru.com/technologies/javascript/11137.asphttp://www.devguru.com/technologies/javascript/10763.asphttp://www.devguru.com/technologies/javascript/11138.asphttp://www.devguru.com/technologies/javascript/11139.asp
  • 8/14/2019 Javascript Material

    41/47

    lowsrc:

    Syntax: Image.lowsrc

    The lowsrc property specifies the URL of a low-resolution version of an imagerelating to the LOWSRC attribute of an IMG tag. A browser first loads a low-resolution version before replacing it with the high-resolution version of the srcproperty.

    name:

    Syntax: Image.name

    The name property is read-only and reflects the NAME attribute of an IMG tag. If theImage object has been created by using the Image constructor, the value ofthis property is null.

    src:

    Syntax: Image.src

    The src property is a string representing the URL of an image and reflects the SRCattribute of an IMG tag. The src property can be altered at any time, but whenyou do so the new image (if not the same size) is scaled to fit the height andwidth attributes of the IMG tag. Also, the loading of any other image into that

    cell is aborted, so the Lowsrc property should be altered before setting the srcproperty.

    vspace:

    Syntax: Image.vspace

    The vspace property is read-only and specifies the VSPACE value of the IMG tag,which is the number of pixels space between the top and bottom margins of animage and surrounding text. For an image created using the Image constructor,the value of this property is null.

    width:

    Syntax: Image.width

    The width property is read-only, and is a string stating the WIDTH attribute of anIMG tag in pixels. Where an image has been created using the Imageconstructor, the width is of the image itself, not the WIDTH value of the display.

    http://www.devguru.com/technologies/javascript/11140.asphttp://www.devguru.com/technologies/javascript/11141.asphttp://www.devguru.com/technologies/javascript/11451.asphttp://www.devguru.com/technologies/javascript/11142.asphttp://www.devguru.com/technologies/javascript/11143.asphttp://www.devguru.com/technologies/javascript/11140.asphttp://www.devguru.com/technologies/javascript/11141.asphttp://www.devguru.com/technologies/javascript/11451.asphttp://www.devguru.com/technologies/javascript/11142.asphttp://www.devguru.com/technologies/javascript/11143.asp
  • 8/14/2019 Javascript Material

    42/47

    Methods:

    handleEvent:

    Syntax: Image.handleEvent(event)

    The handleEvent method is used to evoke the handler for a specified event.

    Window:

    As the top level object in the JavaScript client hierarchy, every browser window andframe has a corresponding Window object, created automatically with everyinstance of a or tag.

    Example:

    Window Object Example

  • 8/14/2019 Javascript Material

    43/47

    window.confirm("Question");window.prompt("Enter ur name:");//window.scrollTo(1000,1000);window.close();

    Properties

    closed:

    Syntax: window.closed

    This property is used to return a Boolean value that determines if a window hasbeen closed. If it has, the value returned is true.

    defaultStatus:

    Syntax: window.defaultStatus( = "message")

    This property is used to define the default message displayed in a window's statusbar.

    document:

    Syntax: window.document

    This property's value is the document object contained within the window. See

    Document object.

    frames:

    Syntax: window.frames("frameID")

    This property is an array containing references to all the named child frames in thecurrent window.

    history:

    This property's value is the window's History object, containing details of the URL'svisited from within that window. See History object.

    location:

    Syntax: window.location

    This property contains details of the current URL of the window and its value isalways the Location object for that window.

    http://www.devguru.com/technologies/JavaScript/10856.asphttp://www.devguru.com/technologies/JavaScript/10857.asphttp://www.devguru.com/technologies/JavaScript/10858.asphttp://www.devguru.com/technologies/JavaScript/10859.asphttp://www.devguru.com/technologies/JavaScript/10860.asphttp://www.devguru.com/technologies/JavaScript/10861.asphttp://www.devguru.com/technologies/JavaScript/10856.asphttp://www.devguru.com/technologies/JavaScript/10857.asphttp://www.devguru.com/technologies/JavaScript/10858.asphttp://www.devguru.com/technologies/JavaScript/10859.asphttp://www.devguru.com/technologies/JavaScript/10860.asphttp://www.devguru.com/technologies/JavaScript/10861.asp
  • 8/14/2019 Javascript Material

    44/47

  • 8/14/2019 Javascript Material

    45/47

    This method is used to close a specified window. If no window reference is supplied,the close() method will close the current active window. Note that this methodwill only close windows created using the open() method; if you attempt toclose a window not created using open(), the user will be prompted to confirmthis action with a dialog box before closing. The single exception to this is if the

    current active window has only one document in its session history. In this casethe closing of the window will not require confirmation.

    confirm:

    Syntax: confirm("message")

    This method brings up a dialog box that prompts the user to select either 'o.k.' or'cancel', the first returning true and the latter, false.

    forward:

    Syntax: window.forward()

    Using this method is the same as clicking the browser's Forward button, i.e. it goesto the next URL in the history list of the current top-level window.

    open:

    Syntax: window.open(URL, name [, features])

    This method is used to open a new browser window.

    prompt:

    Syntax: window.prompt(message[, defaultInput])

    This method displays a dialog box prompting the user for some input.

    scrollTo:

    Syntax: window.scrollTo(coordsPixels)

    This method is used to scroll the window to the supplied co-ordinates.

    Frame:

    A Frame object is created by using the HTML tag in a Window thatcontains the tag. A frame is an independent window within aparent window (in other words, you can display multiple frames, or windows, ona single screen). It has its own URL and is treated, with a few exceptions, as aWindow object by JavaScript (this includes having all the same methods andproperties of a Window object). For more information on Frame objects, go tothe Window object page.

    http://www.devguru.com/technologies/JavaScript/10884.asphttp://www.devguru.com/technologies/JavaScript/10889.asphttp://www.devguru.com/technologies/JavaScript/10894.asphttp://www.devguru.com/technologies/JavaScript/10896.asphttp://www.devguru.com/technologies/JavaScript/10901.asphttp://www.devguru.com/technologies/JavaScript/10884.asphttp://www.devguru.com/technologies/JavaScript/10889.asphttp://www.devguru.com/technologies/JavaScript/10894.asphttp://www.devguru.com/technologies/JavaScript/10896.asphttp://www.devguru.com/technologies/JavaScript/10901.asp
  • 8/14/2019 Javascript Material

    46/47

    Properties

    length:

    Syntax: [windowReference.].frames.length

    [frameReference.].frames.length

    Reflects the number of child frames within a frame.

    parent:

    Syntax: parent.propertyName

    The parent of the current frame. Its a string indicating the name of the windowcontaining the frameset tag.

    self:

    Syntax: self.propertyName

    A synonym for the current frame.

    Methods

    blur:

    Removes focus from the frame

    open:

    Same as Window object open method.

    close:

    Closes the window

    alert:

    Contains the string argument to display message.

  • 8/14/2019 Javascript Material

    47/47