JAVA SCRIPT AND HTML DOM Predefined Objects Java
JAVA SCRIPT AND HTML DOM
Predefined Objects �Java script allows to access the contents of web pages �The components of web pages are represented by objects that are organized in a hierarchical structure called “Document Object Model” represents a parent-child relationship �The top of the object hierarchy is “Window” object represents the entire browser window that display the document.
The window object �Top level in hierarchy �Other objects are either direct or indirect children �This object has many useful properties and methods to get information and to perform specific task.
Properties �Window object provides number of properties to get information about the window itself as well as different parts of the window such as menu bar, address bar and status bar. �Closed: this boolean property indicates whether a window opened using the window. open() method is closed or not. true- if window is closed false-otherwise
Properties contd. . �Default status: specifies default message in window status bar �Name: name to reference the window �Document: An object that contains information about the current document is displayed in the window. �History: An object that contains URLs visited so far �Location: Contains information about the current URL �Event: contains information about the event that occured last. Accessible only from event handlers �Frames: this is an array containing all frames in
Properties contd. . � Length: the number of frames the window cnntains � Navigator: contains information about the browser application. � Screen: Refers to the screen object associated with the window � Scree. Left, Screen. Top: specifies X and Y coordinates respectively of the window, relative to user monitor screen. � Window: A global object refers to the current window � Self: this object is a synonym for the current window � Top: A reference to the top level window in the object hierarchy � Parent: A reference to the parent window � Opener: Reference to the window from which the current window was opened using the open() method � Status: It contains the message of the status bar of
Methods Following are the commonly used methods of the window object �Alert(msg): It pop ups an alert dialogbox. Function show() { alert(“Hi today is “+ new Date()); } <button on. Click=“show()”>Time</button>
Methods contd. . �Blur(): this function takes the focus away from the window on which blur() method is invoked window. blur(); �Close(): closes the browser window on which it is invoked if win referes to some window: win. close(); �Confirm (msg): it is necessary to know user’s choice before doing any crucial task. This metod pops up a dialog box with a message specified as an argument and an OK/Cancel button. Returns true-OK clicked Returns false- Cancel Clicked
Methods contd. . � Focus(): gives focus to the specified window <button on. Click=“opener. focus(); ”> Goto parent window </button> � Move. By(dx, dy): This method changes the position of the specified window by a specified number of pixels. Essentially adds dx to the Screenleft property and dy to Screen. Top and finally place the window in a position as indicated by the Screen. Left and Screen. Top properties. � Move. To(x, y): This method sets the (left, top) corner specified window to the specified coordinates x and y. <input type=“button” on. Click=“move. To(0, 0)” value=“MOVETO”>
Methods Contd. . . �Open([url [, name [, features [, replace ]]]]) This method creates and opens a new browser window and returns a reference to this window. �It takes numerous arguments �All arguments are optional �url: URL of the web page to be opened in new window. If no url is specified, a new window with the URL about: blank is opened �Name: is a string denoting name of the new window. It can have the following values:
Methods contd. . � _blank: Default value. Indicates that the URL is to be loaded in a new window � _self: Indicates that the URL is to be loaded in the current window. It replaces the current page � _parent: Indicates that the URL is to be loaded in the parent window � _ temp: Indicates that the URL is to be loaded in the top-level window � The third optional argument specifies the features and attributes the newly created window will have. It is a common separated list of items, , each of which takes the form of feature-value. The value is either yes/no (1/0) or an integer(pixels) � Refer table 14. 2 The window features. Page no: 451
Methods contd. . . � The last argument indicates whether or not to create a new entry in the history list. The value true indicates the current URL will be replaced by a new URL and the value false indicates that a new entry is created for the new URL in the history list � Print(): this method opens a print dialog box that helps the user to print the contents of the specified window. <button on. Click=“print()”> Print</button> � Prompt(msg, [input]): This method is used to interact with the users. It takes the message as an argument and prompts the user with an input box to enter the data. Name=prompt(“Enter your name”, “”); Alert(‘hi’, + name);
Methods contd. . � resize. By(dx, dy): This method resizes the content window by the specified amount in pixels in the horizontal and vertical directions. � resize. To(x, y): It resize the context window to the specified pixel values. � scroll. By(dx, dy): this method on the window objet scrolls the window by the specified amount in pixels along the horizontal and vertical directions � scroll. To(x, y): It scrolls the window to the specified pixel values � set. Interval(code, interval, [lang]): this method executes a certain piece of code, at regular intervals, specified in milliseconds by interval.
Methods contd. . � The code may be function name or any valid statements written in the language specified by the optional lang argument, which can have the values: Java. Script, Jscript or VBScript. The set. Interval() method creates a new periodic timer. The timer expires after every specified interval. Whenever the timer expires the code is executed. � clear. Interval(ID): It is used to stop the timer created using the set. Interval() method � set. Timeout(code, interval[lang]): this is similar to the set. Interval() method, except that it starts a simple timer, which expires only once after the specified interval in milliseconds. So, it executes a certain piece of code only once. It returns a unique integer that represents the ID of the newly created timer.
Methods contd. . . �clear. Timeout(ID): it is similar clear. Interval() method except thatit stops the timer started by the set. Timeout() method. The clear. Interval() method uses the. ID returned by the set. Interval() method to identify a specific timer to be stopped. �Stop(): This method added in javascript 1. 2 stops the current window from downloading ad rendering the current page. Equals to clicking browser stop button. <input type=“button” value=“stop” on. Click=“window. stop()”> Refer table 14. 3 Methods of the window object. Page: 455 -456
The Location Object �The Java. Script window object has a property location ( accessed by window. location or simply location), which encapsulates the current URL that is displayed in the visitor’s browser. �This object has several properties and methods that may be used to inspect or change different fields of a URL or even change the entire URL. �Following are the properties and methods of the location object
Properties and Methods of Location Object Property Name Description href The entire URL hostname URL host section host URL’s hostname and port section port URL’s port section Pathname URL’s pathname section Search URL’s query string portion Protocol URL protocol name including”: ” Hash URL anchor Methods Reload() Current URL is reloaded Replace(URL) Loads the specified URL by replacing the current one. Does not affect the browser’s history
Reading location object properties � The following code segment reads all the properties of the location object and display them. <html> <head> <title> Location object demo </title> </head> <body> <script language=“Java. Script”> For(i in location) document. writeln(i + “ : “ + location [i] + “ ”); </script> </body> </html>
Changing Location Object � The location object allows us to change individual properties or the entire URL using the following syntax. Location. property. Name=value; The following code segment loads the new URL http: //www. google. com Location. href=http: //www. google. com; The URL is stored in browser’s history if you want to overwrite the previous URL with a new one Location. replace(http: //www. google. com); To reload this page: Location. reload(); // it reloads the current document the one that is contained in the location. href property
The history Object �The window object has another important property history (accessed as window. history or simply history) �It stores information about URLs already visited from the browser’s window. �The list of properties and methods of the history object along with their brief descriptions are given below. Contd. .
Properties and methods of the history object Property Name Description Current document URL Length Number of entries of the history object Next URL in the history object Previous URL in the history object Methods Method Name Description Back() Loads previous URL in the history list Forward() Loads next URL in the history list Go(rel. Pos | string) Loads a specific URL in the history list. The rel. Pos indicates number of places to go, relative to the current position. String argument indicates the specific URL to be loaded.
Properties � Current: This property refers to the complete URL entry of the history object. To access current property of the history object as follows History. current Length: The property of the histroy object returns the number of entries in the history object. History. length Next: the next property of the history object refers to the URL of the next entry in the history list. It is undefined if there is n entry in the current entry. Previous: the previous property of the history object refers to the URL of the previous entry in the history list. Undefined- if there is no entry before the current entry.
Methods �Back(): Used to load previous URL in the browser’s history. No effect if the history doesnot contain any previous URL � history. back(); �forward(): used to load the next in the browser’s history. No effect if the history doesnot contain the next URL �History. forward() �go(): this takes a single argument (either integer or string) �History. go(rel. Pos|string); The integer argument indicates the number of places to go, relative to current position. Positive
The navigator object �Navigator object contains information about the client’s browser such as its name and version. �Some javascript codes do not work on some old browsers. One good idea is to identify the name and version of the visitor’s browser , this way web pages can be made smart enough to function different browsers. �Refer table 14. 6 javascript navigator object properties and methods. Page no: 460
Browsers detection � Website visitors use different types of browsers with different versions. � Major problem is that different browsers respond differntly to different script. Client side code script should give the same output for all browsers. � Knowing information about the browsers being used by the user is sometimes very helpful to the application developer. � The navigator object can be used to retrieve different properties of the browser. All properties are supported by all browsers. � We can use some common properties to identify the browser used and its version.
Example- navigator object � <html> <head> <title> Browser detection </title> </head> <body> <p> This is a paragraph </p> <script language=“Java. Script”> Var name=navigator. appname; If(name== “microsoft internet explorer) Location. href=“ie_version. html”; If(name==“netscape”) Location. href=“nn_version. html”; </script> </body> </html>
Object hierarchy �When an html document is loaded in a browser, the browser creates many java script objects, which vary in their types. �These objects have their respective sets of properties and methods. �These objects are organized in a hierarchical , which represents the HTML document itself. �This hierarchy is sometimes called instance hierarchy with specific instances of objects rather than their classes. �The DOM Document Object Model is the road map through which we can locate any element in
Accessing objects � Many javascript objects are containers of other objets. � Container to contained object relationship is present, but not a class – and – subclass relationship. � The top level object is window, so it can be accessed directly by its name. � Any other object can be referenced by its names, prefixed by the names of all the objects that contain in it. In order, separated by dots. � Ex: window. document. body � Window. document. body. forms[0] and window. document. body. forms[1]
Events �The set of tasks that users may perform on a web page are called interactive events or simply events. �When users click a button a web page , a click event occurs. The buton is called source of the event. �Other events occur due to other user tasks such as mouseover event- moving mouse pointer in hyperlink submit event- submitting a form keystroke event- key press mousedown event- presing a mousebutton
Event handlers �Java. Script identies an event and takes an action by executing some piece of code. The procedure of taking action is called event handling. �The specific Java. Script code that takes the action (handles the event) is called event handler. �The handler of an event is usually provided as a function �An event handler may be interactive or non intteractive depending upon the type of the event it handles. �The name of the property for the event click is on. Click. �Note: The name of the property is case insensitive.
Event handler contd. . �<input type=“button” value=“clickme” on. Click= “alert(you clicked me”); ”> on. Cick-Event alert-event handler. � this tells the java script engine that when the event click occurs, the handler having the single statement alert(msg) should be executed. �To associate the handler event. Handler with the event. Name, the following syntax is uded on. Event. Name=“event. Handler”
Event handlers contd. . �Event. Name must be one of the possible events for the tag. Element. on. Event. Name=event. Handler; Where , element is the source of the event. Refer: table 14. 7 Java. Script events and their scources: page No: 464 And refer examples too
Event Object �In Java. Script an event is represented as a global object called event object. �This event object encapsulates the state of an event such as location of the mouse pointer and left or right button pressed for mouse event, unicode of the key pressed for a key event and so on. �The event object is available only when an event occurs. So, only event handlers can access this event object. �Consider the following example
Example � <html> <head><title> Event object demo </title></head> <body on. Click=“handler()”> <script language=“Java. Script”> Function handler() { Alert(“you clicked at (‘ + event. client. X + ‘, ’ +event. client. Y + ‘)’); } </script> </body> </html>
Key press event-example <html> <head> <title>keycode</title> </head> <body onkeydown=“show. Key(); ”> </body> <script> Function show. Key() { Var str=‘key pressed: ’+String. from. Char. Code(event. keycode); Str=str + ‘, key code: ‘ + event. keycode; Status=str; </script> </html> Refer a table 14. 8 that shows a list of properties available on the event object. Page: 470 -471
Advanced Event Handling �Suppose the element inner is declared inside another element outer. Both outer and inner elements have their respective handlers for the click event. �Clicking on inner also means clicking on outer, this means that the click event will occur on inner as well as on outer. �Consequently handlers for inner as well as outer will be trigged. �Which handler will be called first? The order in which events occur depends on the underlying event propogation model. Two such models exists: event bubbling and event capturing
W 3 C event propagation model � W 3 c provides a specification for the event handling mechanism called “event propagation model” � According to this mechanism event propagation model has two phases: event capturing and event bubblingoccur in the order specified. � Separate handler may be registered for each of these two steps � Whenever an event occur on multiple elements, it starts from the outermost source element and propagates downloads until it reaches the innermost source element of the event. � All the handlers that are set for the capturing phase are executed on its way called event capturing
W 3 c event propagation model �After reaching innnermost source element of the event, it changes in direction and moves up until it reaches the outer most element, all handlers that are set for the bubbling phase are also executed on its way, this phase is called bubbling.
� Note: event continues to propagate even if there is no handler registered for an element, the propagation of the event may be stopped at any time. � Not all the browsers allows us to register handler for the capturing phase. However, all the browsers provide interface that allow us to register a handler for the bubbling phase. � The traditional method for handler registration is nothing but registration for the bubbling phase. Some. Element. on. Some. Event=“some. Handler” this code registers somehandler for the event someevent on some. Element for the bubbling phase. The following code do the same <some. Element on. Some. Event=“some. Handler”>
Example: event handling <html> <head> <title> Event Demo </title> <script language=“Java. Script”> Function handler_body() { Alert(‘you clicked on body’); } Function handlr_p() { Alert(‘you clicked on p’); } </script> </head> <body on. Click=“handler_body()”> <p on. Click=“handler_p()”> A paragraph </p> </body> <html>
Event handling
� Suppose the user clicks on <p>, which handler will be called. Answer is both handlers � W 3 c provides the method add. Event. Listener() on an element that can be used to register a handler for both the capturing and bubbling phase, as follows some. Element. add. Event. Listener(“event. Name”, event. Handler, flag); � this method registers a handler for an event except that a specific event propagation model can be choosen. � Addevent listener () takes three arguments-event name, event handler and flag. Flag indicates this handler is a pat of the capturing or bubbling phase. True- capturing phase, false-bubbling phase
Preventing event propagation �Sometimes, developers want to run an event bubbling off to avoid interference among methods as well as to save system resources �Browsers have to check every ancestor element for a handler that may take significant time. �The upward movement of an event may be cancelled inside any handler. This is done by setting cancel. Bubble property of the event object // event. cancel. Bubble=true;
Example <html> <head> <title> event demo </title> <script language=“Java. Script”> Fucntion handler_body() { Alert(“you clicked on body”); } Fucntion handler_P() { Alert(“you clicked on p”); Event. cancel. Bubble=true; } </script> </head> <body on. Click=“handler_body()”> <p on. Click=“handler_p()”> A paragraph</p> </body> </html> // when the user clicks a <p> element, a click event occurs, which triggers handler_p() inside handler_p(), event bubbling is cancelled by setting cancel. Bubble to true.
Multiple window and frames �Here we discuss how to handle multiple frames using javascipt �In javascript a frame is treated as a separate window. So, a frame has the same set of properties and methods as a window. So we cannot control a frame exactly like a regular window. �we can refer to a form field contained in a frame from another frame, or change the background of one frame from another frame.
Example <html> <frameset cols=“ 20%, 80%> <frame name=“left” src=“left. tml”> <frame name=“right” src=“right. html”> </frameset> </html> � Every frame has a parent frame in which the frame is contained. One frame may refer to other frames. To do this, you must start with the parent frame. � Once you have a reference to the parent frame, you can refer to other frames using the dot(. ) operator and frame’s name. � To access right frame-parent. right
� Framesets are treated as arrays, so the regular array notation or associative array notation may also be used. � Following is the source of the left. html page. The page right. html is a blank page <script language=“java. Script”> Function set (color) { Parent. right. document. bgcolor=color; } </script> <ahref = “Java. Script: set(‘blue’)”> Blue</a> <ahref=“Java. Script: set(‘red’)”>Red</a>
Working with multiple frames �Parent: a reference to the parent frame �Parent. right: a reference to the right frame �Parent. right. docment: a reference to the document object of the right frame �Parent. right. document. bgcolor: the background color property of the document of the right frame.
Scripting iframes �Java script allows us: �Change properties (position, size and background color) of an iframe element from a document. �Communicate with the document from an iframe �Obtain information from an iframe �Passing parameters to an iframe Inline frames or Iframes are blocks used to load separate HTML documents into an existing HTML document. An iframe may appear anywhere in the document. Both java script and CSS may be used to manipulate properties of an iframe.
Iframes � Iframes can be referenced in the same way that frames are referenced, using the frames array i. e. , document. frames. An iframe can access the contained document using its property <html> <head><title> multiple window demo </title></head> <body> <script language=“Java. Script”> Function show(url) { document. frames[0]. location=url; } </script> <iframe id=“panel” scrolling=“yes” wifth=“ 300” height=“ 200”></frame> ahref=Java. Script: show(‘http: //www. yahoo. com’)”>yahoo</a> ahref=Java. Script: show(‘http: //www. google. com’)”>Google</a> </body></html>
Sample output: Accessing iframes
DOM �HTML DOM tree corresponding to an HTML document consists of a set of nodes, each of which represents some part of the HTML document. �All elements, their attributes and their containing text may be accessed through the DOM tree, using the interfaces provided in the HTML DOM specification. �An HTML document is represented as a DOM tree by the browsers. Browsers traverse the DOM tree and render the document on the screen. �Java. Script also provides a mechanism to navigate and manipulate the HTML DOM tree
DOM contd. . �DOM tree-like a forest that can have zero or more trees. �The root of this tree represents the html element. �In addition to DOM interfaces, javascript provides additional facilitates to access an HTML DOM tree. �The document object represent the entire HTML document. �Javascript allows us to access the <html> and <body> elements of an HTML document directly. �The object document. Element and document. body refer to the <html> and <body>
Example �Consider the following HTML page. <html> <head><title>Blank page </title> </head> <body></html>
Advanced javascript and html forms: Form object and Element Forms are important building blocks of web pages. Accessing form Elements: The document. forms object is an array containing all the forms in a page. So document. forms[0] is the first form, document. form[1] is the second and so on. . The child element of an array may be accessed using the elements property of the form object Individual elements can be accessed using either the ordinal number of the frame of the element as an index. Note: the array elements contains only form fields and not other elements such as , <p>, <div>, <span>
Example: <form name=“frmlogin” id=“frmlogin” action=“login. jsp”> Login: <input type=“text” name=“login”> Password: <input type=“password” name=“password”> <input type=“reset” value=“reset”> <input type=“button” value=“login”> </form> Note: form has 4 fields. Br is not a form field Document. forms[0]. elements[0] refers to the first text field Document. forms[0]. elements[3] refers to the login button and so on. . .
Example contd. . . �A reference to a particular form may be obtained using the get. Element. By. Id() method on the document object. �The following statement refers to the form frm login Frm=document. get. Element. By. Id(“frmlogin”); So frm. elements[0] is now the fist text field, frm. elements[1] is the second text field and so on �name of the form fields may also be used to access them. �Frm. login referes to first form field and frm. password refers to the second form field. �Frm. elements[“login”] and
Form methods and properties �Java. Script forms have methods and properties for dealing with them. �submit(): This method is used to submit a form through Java. Script. The form may be submitted by clicking on its submit button. In that case, the handler for the submit event is called inside the handler of submit event To invoke the submit() method on a form object, we must have reference to it. HTMLDOM or other methods may be used to get such a reference. Document. forms[0]. submit();
Methods �Reset(): This method sets the values of the form fields to their default values. Again to invoke this method, you need to have a reference to the form element. document. forms[0]. reset(); �Action(): the action property of the form object is a read/write property that indicates the URL to be loaded when the form is submmitted. document. forms[0]. action=‘check. jsp’;
Advanced javascript and HTML � Conditional compilation: it allows us to execute a certain piece of code, depending on whether IE or other browser is used. � Conditional compilation is activated by using the @cc_on statement and is ended with the @ statement. . These statements are written inside a comment. . � So, if the browser is IE it parses the comment and executes the conditional compilation construct , non-IE browsers simply ignore the comment. � /*cc_on alert(“hello, you are using IE: ”); @*/ The conditional compilation construct @cc_on Alert(“hello you are using IE”); @
Formatting numbers �Sometimes we may want to display a specific number of digits after the decimal point. �For example, if we want to display only two digits after the decimal point for currency data. Java script provides two functions on numbers to format them. �to. Fixed(n): this function formats any number z for n number of digits after the decimal point. The number is rounded up and padded with zeros as when necessary. �Ex: no=20. 3246 Result=no. to. Fixed(3)// result is 20. 325 result=no. fixed(2)// result is 20. 32
Formatting numbers �To. Precision(n): this function formats any function z , that it has exactly a ‘n’ number of total digits. The number is rounded up and padded zeros as when necessary. �No=20. 3246 result=no. to. Precision(5) // result is 20. 324 result=no. to. Precision(4) // result is 20. 32 result=no. to. Precision(8) // result is 20. 324600
Tabular data control � Microsoft Internet Explorer version 4 and above support a special Active X control called Tabular Data Control (TDC). � It allows to access and display information stored in ASCII text files. TDC effectively provides simple database function without any server-side script. � Netscape requires a plug-in for TDC to work � TDC is intialized with the HTML <object> tag, with the classid attribute set to CLSID: 333 C 7 BC 4 -460 F-11 D 0 BC 04 -0080 C 7055 A 83 as follows <object id=“obj” classid=“clsid: 333 c 7 bc 4 -460 f-11 d 0 bc 04 -0080 c 7055 a 83”> -----</object>
Object element � Object element has a number of parameters that are specified by the <param> tags. � Data. URL: the URL of the Data File. � Use. Header: this boolean parameter specifies whether the first line of the data contains column headers that can be referenced for their respective fields. If false is specified columns are retrieved as column 1 , column 2 etc. . � Text. Qualifier: this optional parameter indicates the character that surrounds a field � Field. Delim: specifies the field separator. The default delimeter is comma, � Row. Delim: specifies the end of the row character. The defalt character is the newline character. For example Refer: 508
Daty entry and validation �Checking a non-empty text/password field �Restricting length of text/password field �Tables and forms �DHTML with javascript
- Slides: 68