44
CNIT 133 Interactive Web Pags – JavaScript and AJAX Window Object

CNIT 133 Interactive Web Pags – JavaScript and AJAX

Embed Size (px)

DESCRIPTION

CNIT 133 Interactive Web Pags – JavaScript and AJAX. Window Object. Agenda. My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes). The window object. The document object. The location object. The history object. The navigator object. The onerror property/handler. - PowerPoint PPT Presentation

Citation preview

Page 1: CNIT 133 Interactive Web Pags – JavaScript and AJAX

CNIT 133 Interactive Web Pags –JavaScript and AJAX

Window Object

Page 2: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Agenda

• My Web Site: http://fog.ccsf.edu/~hyip (download syllabus, class notes).

• The window object.• The document object.• The location object.• The history object.• The navigator object.• The onerror property/handler.• Window Methods.

Page 3: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window and Document Objects

Window Object(Global Object)

document object(DOM)

location object

history object(array)

navigator object

self

opener

alert()back()blur()

clearInterval()clearTimeout()

close()confirm()focus()

forward()home()open()print()

prompt()setInterval()setTimeout()

stop()

Window Properties

Window Methods

Document Object Collection:images[]forms[]links[]

anchors[]

Document Object Properties:lastModified

titleURL

Document Object Methods:close()

getElementById()getElementsByName()

getElementsByTagname()open()write()

Page 4: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Window Object (Global Object) - Properties

• Window Properties document: document object Location: location object history: history object (array). history.back(), history.forward(),

history.go() navigator: navigator object (Browser information) self: Refers to the current window. Equivalent to window opener: Refers to the window from which a particular window was

opened close: Boolean value, window has been closed or not defaultStatus: set or return default text in status bar name: set or return name of window

Page 5: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Window Object (Global Object) - Methods

• Window Methodsalert()back()blur()clearInterval()clearTimeout()close()confirm()focus()

Page 6: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Window Object (Global Object)- Methods

forward()home()open()print()prompt()setInterval()setTimeout()stop()

Page 7: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Window Object – Properties sample

<html><head><title>Window Object properties</title></head><body><h1>Window Object properties</h1><script language="JavaScript" type="text/javascript">document.write("closed (boolean - window has been closed or not): ", closed, "<br>");document.write("defaultStatus (set or return default text in statusbar): ", defaultStatus, "<br>");document.write("name (set or return name of window): ", name, "<br>");</script></body></html>

Page 8: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Document Object - Properties

• Document object collection:images[]forms[]

elements[] (button, checkbox, hidden, password, radio, reset, select, submit, text, textarea)

links[]anchors[]

• Document object properties:lastModifiedtitleURLlocation (deprecated since Netscape 6, use URL instead)

Page 9: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Document Object - Methods

• Document object methods:close()getElementById()getElementsByName()getElementsByTagname()open()write()writeln()

Page 10: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Document Object - Properties sample

<html><head><title>document Object properties</title></head><body><h1>document Object properties</h1><script language="JavaScript" type="text/javascript">document.write("domain (return domain name): ", document.domain, "<br>");document.write("lastModified (return last modified date): ", document.lastModified, "<br>");document.write("referrer (return the URL of the document that loaded the current document): ", document.referrer, "<br>");document.write("title (set or return the title of the document): ", document.title, "<br>");document.write("URL (return the full URL of the document): ", document.URL, "<br>");document.write("location (deprecated, use document.URL): ", document.location, "<br>");</script></body></html>

Page 11: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Location Object• The location property of a window (or frame) is a reference to

a Location object; it represents the URL of the document currently being displayed in that window.

• The href property of the Location object is a string that contains the complete text of the URL.

• The toString() method of the Location object returns the value of the href property, so you can use location.toString() in place of location.href:

location.href location.toString() /* this 2 statements are the same */

Page 12: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Loading New Documents• Although the location property of a window refers to a

Location object, you can assign a string value to the property. • When you do this, the browser interprets the string as a URL

and attempt to load and display the document at the URL:/* if the browser does not support the document.getElementById function, redirect to a static page. */if (!document.getElementById) {

location = "staticpage.html";}

• Historically, assigning a URL to the location property of a window has been the supported technique for loading new pages.

Page 13: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Location Object• The Location object have two methods with related purposes:

The reload() method reloads the currently displayed page from the web server;

The replace() method loads and displays a URL that you specify. When you call this method, the specified URL replaces the current one in the browser’s history list rather than creating a new entry in that history list. Therefore, the Back button does not take the user back to the original document.

• Finally, the location property of the Window object refers to a Location object. The deprecated location property of the Document object is simply a read-only string (deprecated since Netscape 6, use document.URL instead). document.location is a synonym for document.URL

• In most cases, document.location/document.URL is the same as location.href. When there is a server redirect, however, document.location/document.URL contains the URL as loaded, and location.href contains the URL as originally requested.

Page 14: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Location Object sample<html><head><title>location Object properties</title></head><body><h1>location Object properties</h1><script language="JavaScript" type="text/javascript">document.write("host (return hostname and port of a URL): ", location.host, "<br>");document.write("hostname (return the hostname of a URL): ", location.hostname, "<br>");document.write("href (return the entire URL): ", location.href, "<br>");document.write("pathname (return path name of a URL): ", location.pathname, "<br>");document.write("port (return the port number the server uses for a URL): ", location.port, "<br>");document.write("protocol (return the protocol): ", location.protocol, "<br>");document.write("search (return the query portion of a URL): ", location.search, "<br>")</script></body></html>

Page 15: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The History Object• The history property of the Window object refers to the History object for

the window. • For security and privacy reasons, the array elements of the History object

are never actually accessible to scripts.• Although its array elements are inaccessible, the History object supports

three methods: The back() and forward() methods move backward or forward in a

window’s (or frame’s) browsing history, replacing the currently displayed document with a previously viewed one.

The go() method, takes an integer argument and can skip any number of pages forward (for positive arguments) or backward (for negative arguments) in the history list.

history.back() history.forward() history.go(+2) history.go(-3)

Page 16: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The History Object sample<html><head><title>history Object properties</title></head><body><h1>history Object properties</h1><script language="JavaScript" type="text/javascript">document.write("length (return the number of URLs in the history list): ", history.length, "<br>");

document.write("History has three methods - back(), forward(), and go()");

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

Page 17: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Obtaining Window, Screen, and Browser Information

• The navigator property of a Window object refers to a Navigator object that contains information about the web browser as a whole.

• In the past, the Navigator object was commonly used by scripts to determine if they were running in Internet Explorer or Netscape.

• This browser-sniffing approach is replaced by a capability-testing approach:

if (window.addEventListener) {// addEventListener() method supports by Netscape/Mozilla/Firefox

}else if (window.attachEvent) {

// attachEvent() method supports by IE}else {

// old browsers}

Page 18: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Navigator Object• Browser sniffing is sometimes still valuable, however, one such case is

when you need to work around a specific bug that exists in a specific version of a specific browser. The Navigator object lets you do this.

• The Navigator object has five properties that provide version information about the browser that is running: appName; appVersion; userAgent; appCodeName; platform.

• The following lines of JavaScript code display each Navigator object property in a dialog box:

var browser = "BROWSER INFORMATION: \n";for (var propname in navigator) {

browser += propname + ": " + navigator[propname] + "\n";}alert(browser);

Page 19: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Navigator Object• Client sniffer (

http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html)

/* this module defines an object named “browser”that is easier to use than the “navigator” object*/var browser = {

version: parseInt(navigator.appVersion),isNetscape: navigator.appName.indexOf("Netscape") != -1,isMicrosoft: navigator.appName.indexOf("Microsoft") != -1};

• This is one of the reasons that browser sniffing has become less useful and is being superseded by capability testing.

Page 20: CNIT 133 Interactive Web Pags – JavaScript and AJAX

The Navigator Object sample<html><head><title>navigator Object properties</title></head><body><h1>navigator Object properties</h1><script language="JavaScript" type="text/javascript">document.write("appCodeName (return the code name of browser): ", navigator.appCodeName, "<br>");document.write("appName (return the name of the browser): ", navigator.appName, "<br>");document.write("appVersion (return the version information of the browser): ", navigator.appVersion, "<br>");document.write("cookieEnabled (determine whether cookies are enabled in the browser): ", navigator.cookieEnabled, "<br>");document.write("platform (return which platform browser is compiled): ", navigator.platform, "<br>");document.write("userAgent (return the user-agent header sent by the browser to the server): ", navigator.userAgent, "<br>");document.write("<br><br>");document.write("javaEnabled() (method-Specifies whether or not the browser has java enabled): ", navigator.javaEnabled(),

"<br>");</script></body></html>

Page 21: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window Methods (Opening and Manipulating Windows)

• The Window object defines several methods allow you to open and close windows, control window position and size, request and relinquish keyboard focus, and scroll the contents of a window.

Page 22: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Opening Windows – Window Method open()

• You can open a new web browser window with the open() method of the Window object.

• window.open() takes four optional arguments and returns a Window object that represents the newly opened window:

window.oprn("URL", "winname", "featureslist", booleanvalue); URL: URL of the document to display in the new window. If omitted or null or

empty string, the window will be empty Winname: the name of the window Featureslist: list of features that specify the window size and GUI decorations. Booleanvalue: specifies whether the URL specified as the first argument

should replace the current entry in the window’s browsing history (true) or create a new entry in the window’s browsing history (false), which is the default behaviorvar w = window.open("smallwin.html", "smallwin", "width=400,height=350,status=yes,resizable=yes");

• The return value of the open() method is the Window object that represents the newly created window.

• The opener property of a window refers to the window from which it was opened. If the window was created by the user, the opener property is null.

Page 23: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Closing Windows – Window Method close()

• The close() method closes the current window.• If you create a Window object w, you can close it

with:w.close();

• JavaScript code running within that window itself can close it with:

window.close();• Note: the explicit use of the window identifier to

distinguish the close() method of the Window object from the close() method of the Document object (document.close( )).

Page 24: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Keyboard Focus and Visibility – Window Method focus() and blur()• Calling focus( ) requests that the system give

keyboard focus to the window• Calling blur( ) relinquishes keyboard focus• Note: the focus( ) method ensures that the

window is visible by moving it to the top of the stacking order.

Page 25: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Simple Dialog Boxes – Window Methods alert() confirm() prompt()• The Window object provides three methods for

displaying simple dialog boxes to the user.• alert( ) displays a message to the user and waits for

the user to dismiss the dialog (use for debugging)• confirm( ) asks the user to click an OK or Cancel

button to confirm or cancel an operation• prompt( ) asks the user to enter a string

Page 26: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Error Handling – onerror property/handler

• The onerror property of a Window object is special. If you assign a function to this property, the function is invoked whenever a JavaScript error occurs in that window: the function you assign becomes an error handler for the window.

• Three arguments are passed to an error handler when a JavaScript error occurs:The first argument is a message describing the errorThe second argument is a string that contains the URL of the

document containing the JavaScript code that caused the error

The third argument is the line number within the document where the error occurred

• If the onerror handler returns true, it tells the browser that the handler has handled the error and that no further action is necessary.

Page 27: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Error Handling – onerror property/handler

• Define an error handler that handles all errors silently:// don’t bother the user with error messageswindow.onerror = function() { return true; }

• Display error message:<html><head><title>window onerror property</title><script language="JavaScript" type="text/javascript">/* comment out the following code to see the original error message. */window.onerror = function (message, url, linenum) {

alert("There is an error!!");alert("Error Message: " + message + "\n URL: " + url + "\n Line Number: " + linenum);return true;

}</script></head><body><h1>Window onerror property/onerror event handler</h1><script language="JavaScript" type="text/javascript">document.write("No error");document.write("With error here“</script></body></html>

Page 28: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window Synonyms

Property/synonym Descriptionself Refers to the current

window. Equivalent to window

window The window object has a window property, which identifies the current window being referenced

Opener Refers to the window from which a particular window was opened

Page 29: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Targeting Windows sample

<html><head><title>Window target</title></head><body><a href="somepage.html" target="???">Some

page</a></body></html>

Page 30: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Targeting WindowsTarget Name Description

_self default. If no target is specified. The file listed in the href attribute loads into the window it was requested from.

_blank Loads the file listed in the href attribute into a new, unnamed broswer window.

_parent Loads the file designated in the href attribute file into the parent frame or window.

_top Loads the file specified in the href attribute into the entire current window, above all framesets.

WindowName/FrameName Loads the file into the window or frame with the specified target name. if no window/frame exists with that name, it opens a new window and assigns it that name. you cannot see the window name. the window is simply known by that name in memory

Page 31: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window MethodsMethod Description

alert(text) Displays an alert dialog box containing the text specified and an OK button.

back() Equivalent to the visitor pressing the Back button.

blur() Removes focus from the window.

clearInterval(intervalID) Clears an interval.

clearTimeout(timeoutID) Clears a timeout.

Page 32: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window MethodsMethod Description

close() Closes the window. If you call close alone, JS assumes that you mean the current window and closes it.The close method only closes windows you’ve opened using the open method. In an event handler, you must specify windowObjectName.close() instead of simply using close(). In an event handler, without specifying a window object name is equivalent to document.close().

confirm(text) Displays a confirm dialog box containing the text specified and options for the user to choose OK or CANCEL.

Page 33: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window MethodsMethod Description

focus() Gives focus to a window.

forward() Equivalent to the visitor pressing the Forward button.

home() Equivalent to the visitor pressing the Home button.

open(url, name [, windowFeatures]) Opens a window, loads the document at the specified URL, and gives the window the provided target name and listed features.

print() Print the contents of a window or frame.

prompt(request, defaultInput) Displays a prompt dialog box with the specified request for input from the user. If defaultInput is not supplied, undefined appears in the dialog box (not very pretty).

Page 34: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window MethodsMethod Description

setInterval(‘expression”, msec)setInterval(function, msec)

Evaluates an expression or calls a function repeatedly, every so many milliseconds (msec). The calls continue to fire until the interval is canceled using the clearInterval method, or closing the browser.

setTimeout(“expression”, msec)setTimeout(function, msec)

Evaluates an expression or calls a function after a specified amount of time. It does not act repeatedly.setTimeout does not stall the script, the script continues execution immediately after the call, which simply schedules some future event.

stop() Stops the current document download. Equivalent to the visitor pressing the STOP button.

Page 35: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Opening a pop-up Window – Window Method open()

• [windowObjectName=] [window.] open("URL", "targetName" [, "features"])

• windowObjectName: specifies the name of the window object variable. It is used to call methods on the window and access the window properties.

• URL: specifies the URL of the file to open in the new window. If you want to write to the new window dynamically, do not specify a URL, just provide empty quotes ("").

• targetName: name to be used in the target attribute of an <a> tag. It can only be alphanumeric or underscore.

• features: comma-separated list (without spaces) of any of the following options and values.

Page 36: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Opening a pop-up WindowOption/Values Description

toolbar[=yes|no] | [=1|0] Toolbar with buttons such as Back and Forward.

locationbar[=yes|no] | [=1|0] Location bar where a URL can be entered.

directories[=yes|no] | [=1|0] Standard browser directory buttons. The browser determines which directory buttons appear.

statusbar[=yes|no] | [=1|0] Status bar at the bottom of the window where messages, download status, and link URLs typically display.

menubar[=yes|no] | [=1|0] Browser menu bar with items such as File, Edit, View and Help

scrollbars[=yes|no] | [=1|0] When set to yes, provides scrollbars if the content is too large for the window.

Page 37: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Opening a pop-up WindowOption/Values Description

resizable[=yes|no] | [=1|0] Determines whether the user is allowed to resize the window or not.

innerWidth=pixels the width of the window’s content area in pixels.

innerHeight=pixels The height of the window’s content area in pixels.

outerWidth=pixels The horizontal dimension of the window’s outside boundary, in pixels.

outerHeight=pixels The vertical dimension of the window’s outside boundary, in pixels.

left=pixels The position of the top left corner of the window measured in pixels from the left side of the screen.

Page 38: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Opening a pop-up WindowOption/Values Description

top=pixels The position of the top left corner of the window measured in pixels from the top of the screen.

titlebar[=yes|no] | [1|0] The title bar across the top of the browser window, which displays a document’s title.

myWin = window.open(“test.html”,“TestWin”,“height=100,width=100,status”);myWin = window.open(“test.html”,“TestWin”,“height=100,width=100,status=yes”);myMap = window.open(“map.html”, “MapWin”, “width=150,height=150, toolbar,status”);

Page 39: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Closing a pop-up Window – Window Method close()

• Call the close method with the window’s name

• To close myMap: myMap.close();

Page 40: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Opening and Closing a Pop-up Window sample

<html><head><title>Open and close pop-up window</title><script language="JavaScript">var map = null;function showMap() {

var features = "width=620, height=650";features += ", left=50, top=50,status";map = window.open("map.html", "MapWin", features);map.focus();

}function closeMap() {

if (map != null) {map.close();map = null;

} }</script></head><body><h1>Contact us (CCSF)</h1><p>50 Phelan Avenue<br/>San Francisco, CA 94112<br/>(415) 239-3000</p><p><a href="javascript: void(0)" onclick="showMap()">View Map</a> | <a href="http://www.ccsf.edu/Offices/Office_of_Instruction/Access_Guide/" target="MapWin">View Driving Directions</a> |<a href="javascript: void(0)" onclick = "closeMap()">Close Map</a></p>

</body></html>

Page 41: CNIT 133 Interactive Web Pags – JavaScript and AJAX

map.html<html><head><title>Map file</title></head><body><div align="center"><h2>Map to CCSF</h2><img src="ccsf_map.bmp" border="0" alt="CCSF_MAP" width="400" height="400">

<form><input type="button" value="Print" onclick="window.print()"><input type="button" value="Return" onclick="opener.focus()"><input type="button" value="Close" onclick="self.close()"></form></div></body></html>

Page 42: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Pop-up News<html><head><title>Popup News</title><script language="JavaScript">function showNews() {

news = window.open("http://www.cnn.com", "NewsWin", "width=200, height=220");var newsTimer = setTimeout("news.close()", "20000");

}</script></head><body onload="showNews()"><h2>Popup News</h2></body></html>

Page 43: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Window Methods (Timers)• The core JavaScript language does not provide ability to

schedule code to be executed at some point in the future, but client-side JavaScript does provide it in the form of the global functions setTimeout(), clearTimeout(), setInterval(), and clearInterval().

• The setTimeout() method of the Window object schedules a function to run after a specified number of miliseconds elapses. It returns an opaque value that can be passed to clearTimeout() to cancel the execution of the scheduled function.

• The setInterval() invokes the specified function repeatedly at intervals of the specified number of miliseconds. It returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function.

Page 44: CNIT 133 Interactive Web Pags – JavaScript and AJAX

Writing to Window dynamically sample

<html><head><title>dynamic window text</title><script language="JavaScript" type="text/javascript">function dynWrite() {var topDoc = "<html><head><title>Dynamic text</title></head>";topDoc += "<body bgcolor='yellow' text='black'>";var endDoc = "</body></html>";var features = "width='200',height='200'";

var newWin = window.open("", "DynWin", features);

newWin.document.write(topDoc, "<h2>Dynamically write text</h2>");newWin.document.write("Quote of the day: Please turn in your homework. Thanks.");newWin.document.write("<div align='center'>", "<input type='button' value='close' onClick='self.close()'></div>");newWin.document.write(endDoc);

}

</script></head><body onLoad="dynWrite()"><h1>Home page of some web site</h1>

</body></html>