This is the seventh in a series that will introduce you to the JavaScript language.
In previous articles you have seen the document object in use. We have used document.forms, document.getElementById, document.createElement and several other functions that are built into the document object. In this article we will thoroughly examine the document object and the window object, both of which offer many useful functions. The document object represents the actual content of your page and as such, has functions to help you modify the page itself. We write to a page using document.write, for example, and we access forms using document.forms, as you have seen before. As mentioned in Article #6, everything on your page is the child or parent of something else. It’s all a big tree. The window object is at the very top of that tree and everything else is contained within it. The window object references exactly what it sounds like: your actual browser window. If you want to open a new window or resize the current one, for example, you would be using functions in the window object to do this. In addition to being at the top of the DOM, the window object is also the global object. If you remember from Article #2 of this series, all variables are either in a global or local scope. If they are in the global scope they are accessible from anywhere in your JavaScript. Being in the global scope also means that the variable is attached directly to the window object. Any JavaScript code you write that is not in another function is in the global window object. Because of this we do not need to type “window.” when referring to functions or variables in the window object as you do with some other functions such as document.getElementById. alert() is an example of such a function that we can access either via “window.alert()” or simply “alert()”.Property | Current Value | Description |
window.location | returns the current URL for the window. | |
window.opener | If the window was opened by another window (using window.open), this returns a reference to the window that opened it. | |
MSIE: window.screenTop Other: window.screenY |
returns the top position of the window. Note that these values given in MSIE are drastically different from other browsers. MSIE returns the top position of the content area (below your address bar, back buttons, etc). Other browsers return the position of the top of the actual window (above the close button). | |
MSIE: window.screenLeft Other: window.screenX |
returns the left position of the window with the same problems as screenTop and screenY. |
URL: | http://www.somesite.com/page.asp |
Query String: | action=browse&id=5 |
Anchor: | someAnchor |
function queryString(val){ var q = unescape(location.search.substr(1)).split('&'); for(var i=0; i<q.length; i++){ var t=q[i].split('='); if(t[0].toLowerCase()==val.toLowerCase()) return t[1]; } return ''; }
With this function and our previous URL, queryString(‘action’) would return ‘browse’. We run into a new function here, “window.unescape”. unescape, as well as its complimentary function escape, are both used in conjunction with window.location. When you pass data in a query string it needs to be “escaped” to prevent it from interfering with the query string itself. If your data had a ampersand (&) in it, for example, you would need to escape it so that you could tell the difference between your & and an & that seperates two different values. escape prepares data to be sent to be a querystring value so you would use this when setting window.location. For example:
window.location='/page.asp?name='+escape(SomeInputBox.value);
unescape does the opposite and allows you to get “normal” text from window.location.
Going back to our window properties, we have a property called “opener”. opener is used in conjunction with a commonly used function, window.open. window.open allows us to open a new browser window and, for certain properties, control how it is displayed.var newWindow=window.open('', 'TestWindow', 'width=200,height=200'); newWindow.document.write('This window will close in 2 seconds'); setTimeout(function(){ newWindow.close(); }, 2000);
The 3rd argument of window.open takes a string of arguments. The commonly used ones are:
width, height | sets the dimensions of the window |
left, top | sets the position of the window on the screen |
location, menubar, toolbar, status, titlebar, scrollbars | These options display/hide their respective “bars” from the window. Set to “yes” to show the “bar”. |
resizable | If set to “yes” the window can be resized |
var myTimeout = setTimeout("alert('Hi!');", 500); clearTimeout(myTimeout);
If you did not save the reference, the myTimeout variable, there is no way to clear the Timeout or Interval. Now let’s take a look at an example of this in action:
function createTimeout(text, time){ setTimeout("alert('"+text+"');", time); } var intervals = []; function createInterval(text, time){ // store the interval in intervals array intervals.push(setInterval("alert('"+text+"');", time)); } function tut5(){ if(intervals.length==0) return; // clear the last interval in intervals array clearInterval(intervals.pop()); }
<!--page1.html--> <HTML> <HEAD> <script type="text/javascript">
window.open('page2.html', 'TestWindow', 'width=500,height=200,resizable=yes');
</script> </HEAD> </HTML> <!--page2.html--> <HTML> <HEAD> <script type="text/javascript">
document.write('The URL of the parent window is: '+window.opener.location);
</script> </HEAD> </HTML>
Note that this only works if the URL of the window you are opening is on the same server as the page you are currently on. If we were to open a window to http://www.webreference.com, for example, we would not have access to any properties of that window, nor would Google have access to this page. This is done by all major browsers for security reasons.
Property | Description | Property.length value on this page |
document.forms | An array containing all the forms on the current page | |
document.images | An array containing all the images on the current page | |
document.links | An array containing all the links on the current page | |
document.anchors | An array containing all the anchors on the current page | |
document.applets | An array containing all the applets on the current page | |
document.styleSheets | An array containing all the stylesheets on the current page | |
window.frames | An array containing all the frames on the current page |
Property | Description |
document.getElementById | Returns one element based on its ID |
document.getElementsByName | Returns an array of elements specified by their Name. Unlike an ID, many elements can have the same name on a page. |
document.getElementsByTagName | Returns an array of elements specified by their Tag Name. The Tag Name is simply the name of the HTML tag, ie ‘DIV’, ‘IMG’, ‘TABLE’, ‘A’, etc. |
function getScrollPos(){ if (window.pageYOffset){ return {y:window.pageYOffset, x:window.pageXOffset}; } if(document.documentElement && document.documentElement.scrollTop){ return {y:document.documentElement.scrollTop, x:document.documentElement.scrollLeft}; } if(document.body){ return {y:document.body.scrollTop, x:document.body.scrollLeft}; } return {x:0, y:0}; } function getWindowDims(){ if (window.innerWidth){ return {w:window.innerWidth, h:window.innerHeight}; } if (document.documentElement && document.documentElement.clientWidth){ return {w:document.documentElement.clientWidth, h:document.documentElement.cliendHeight}; } if (document.body){ return {w:document.body.clientWidth, h:document.body.clientHeight}; } return {w:0, h:0} }
Scroll Position | |
Window Dimensions |
The final three properties of document are title, referer and cookies. document.title and document.referer are very straight-forward. document.title contains the title of your page. You can read this and change it after the document has completely loaded. document.referer simply contains the URL of the page that brought you to the current page. So if you clicked on a link to get to this page, document.referer will contain the URL of the page that link was on. If you came directly to this page by pasting it into your address bar, document.referer will be undefined.
document.title | |
document.referer |
function writeCookie(name, value, days){ if(days){ (time = new Date()).setTime(new Date().getTime()+days*24*60*60*1000); var exp = '; expires='+time.toGMTString(); }else{ var exp=''; } document.cookie=name+"="+value+exp+"; path=/"; } function readCookie(name){ var cookies = document.cookie.split(';'); for(var i=0; i<cookies.length; i++){ var cookie=cookies[i].replace(/^s+/, ''); if (cookie.indexOf(name+'=')==0) return cookie.substring(name.length+1); } return null; } function eraseCookie(name){ writeCookie(name, "", -1); }
These three functions do exactly what the say: write, read or erase a cookie from the current page. We can test them out with the following:
function addToCounter(){ var counter = readCookie('myCounter'); if(counter){ counter = parseInt(counter); } else { counter = 0; } writeCookie('myCounter', counter+1, 1); } function showCounter(){ alert(readCookie('myCounter')); }