Thursday, December 5, 2024

Javascript Basics Part 7


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()”.

The Window Object

To start with, the window object gives us access to information about the window:

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.

We rarely need to know where the window is on the user’s screen but the other two properties, location and opener are both very useful. window.location serves two purposes. If you change it with javascript, window.location=’https://www.htmlgoodies.com’, the browser will get redirected to that page. Reading window.location gives you the address of the current document. Why would you need to know this? In general you don’t care about the address of the page, but you might care about the querystring or the anchor. Take the following URL for instance: http://www.somesite.com/page.asp?action=browse&id=5#someAnchor. This URL can be broken into 3 parts:

URL: http://www.somesite.com/page.asp
Query String: action=browse&id=5
Anchor: someAnchor

Since window.location contains all of this information, we can write a function that will return a querystring variable. This is similiar to request.querystring in ASP or $_GET in PHP if you are familiar with either of those languages:

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.

Popup blockers very often will prevent windows from being opened with window.open unless a mouse-click is involved. So if you have a call to window.open in your code without the user clicking on a link or something similiar, it will very likely not work.

window.open takes up to 3 arguments: the URL of the window you want to open, the name of the window, and the properties of the window.

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

For a full reference on window.open please see Mozilla’s Documentation.

Since we are opening a blank window, our first argument is blank. If we were opening a page, ‘test.html’, our call would look like: window.open(‘test.html’, ‘TestWindow’, ‘width=200,height=200’).

In this example, our newWindow variable is set to the window object of the window we opened. Because of this we need to use “newWindow.document.write” to write content to the window.

window.open also has its counter-part, window.close. window.close, however, can only be successfully called on JavaScript-created windows. If you try to close a non JavaScript created window, one of two things will happen: You will either get an alert saying that script is trying to close the window, or your browser will just ignore you.

setTimeout and setInterval

You’ll notice that we are using another new function in this example: setTimeout. setTimeout and setInterval are both used to execute code after a specified amount of time, and they both take two arguments: a function or string of code, and a period to wait in ms. 1ms = 1/1000th of a second, so if you want your code to execute in 5 seconds you need to specify 5,000 for the 2nd argument here.

setTimeout will execute your code one time after the time has elapsed. setInterval will continue to execute your code after each interval. Set to 5,000, setInterval would execute your code every 5 seconds.

There are two other functions, clearTimeout and clearInterval that cancel Timeouts or Intervals you have set. In order to do this, however, you need to have a reference to the setTimeout or setInterval call, i.e:

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());
}
Demo
Text to alert:
Time to wait (in ms):


There is also a clearTimeout function that is identical in syntax to clearInterval

It is important to note that while you are waiting for setTimeout or setInterval to run your code, all of your other JavaScript code still runs. Once setTimeout or setInterval is ready, it will then run your code, but only after any other code is done executing. In other words setTimeout and setInterval will never interrupt other code in order to run.

window.opener

As stated earlier, we can use the ‘opener’ property of window to access the window that opened the current one, as well as any properties, functions, etc of that window. For example:

<!--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.

The Document Object (window.document)

One of the most often-used functions in JavaScript is document.write. Put simply, document.write takes a string and writes it out to the page. The only thing to look out for here is that if the page is completely loaded and you use document.write, the entire page will be cleared and you will only have the result of document.write on your screen.

You have already seen various properties of the document object being used. document.forms, for instance, returns an array of all forms on the page. There are several properties similiar to this:

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

As you saw in our Last Article, almost any of these properties can be duplicated with document.getElementsByTagName. To get all the images on a page, for example, you could use document.getElementsByTagName(‘IMG’);. There are 3 functions similiar to this:

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.

There is one other property, document.all, that gives you an array of every element on the page. document.all is not supported by every browser, however, so it is suggested that you use document.getElementsByTagName(‘*’) instead which will also return every element on the page.

document.body and document.documentElement

document.body refers to the <BODY> tag of your website, where all your content is supposed to be. The entire DOM of your site is nested under document.body. In addition to this, we must use document.body to determine if the document is scrolled and to get the window size. Unfortunately doing this is one of the most convoluted things that exists in web browsers today.

There is a concept called a “Document Type” that gives your web browser a certain set of rules to follow. Changing this DocType makes some properties jump from document.body to document.documentElement, but only some properties and only on some browsers. Put simply, this is a mess so the following two functions will give you the scroll position and window dimensions (hopefully) regardless of your browser.

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
title, referer

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

cookies

Our final topic for this article, cookies, are different than anything else in JavaScript. A cookie is a string of text that you can store from one page to another, as long as you are on the same server. Unlike other variables in JavaScript, a cookie will not get erased when you reload the page. Instead a cookie only gets erased after an elapsed period of time or when you clear all of the cookies from your browser.

Cookies are both read and written from document.cookie. Unlike other properties, changing document.cookie does not actually overwrite it, it adds to it. So if you want to set 5 cookies you set them each with document.cookie = “…”;. The format of a cookie is somewhat particular so we have a few functions to help us out:

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'));
}


If you add to the cookie counter a few times, refresh this page and then show the counter, you will notice that it is still like it was before you refreshed the page. This cookie will be saved either until you clear the cookies from your browser or once 24 hours pass – the cookie is set to expire in 1 day.

That just about covers all the necessities of the window and document objects. Our next article will start to talk about Object-Oriented code.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured