Thursday, February 5, 2009

Java Script Objects


An object is an element in the current Web browsing session. It can be visible, such as a button, image or hyperlink, or it can be invisible, such as the browser name, or history list. Each object has a name and is arranged in a hierarchy, stemming from the parent object, called the window. Each object has a number of properties and methods which do various things.

We use objects in two ways - we can check the current status of an object by assigning the value of one of its properties to a variable, ie, password = document.form.textbox.value. We can also change the value of the property by assigning it a new one, ie, document.form.textbox.value = "Type here".

date Object

A variable can contain a date by writing

var variable = new Date();

The variable will then contain the current date and time and can be manipulated using the following methods:

getDay(), getDate(), getHours(), getMinutes(), getMonth(), getSeconds(), getTime(), getYear() - these methods all return part of the date.

setDate(date), setHours(hours), setMinutes(minutes), setMonth(month), setSeconds(seconds), setTime(time), setYear(year) - these methods can be used to set the values of the date object to what you specify.

toGMTString() - returns the date in GMT format, ie, "Sat,21 Feb 1998 17:29:45 GMT".

toLocaleString() - returns the date in "locale" format, ie, "02/21/98 17:29:45" (American date format).

parse(date) - the setTime method requires the time in a specific format. You can use the parse method to convert a date string (such as one from toGTMTString) into this special format.

document Object

The document object contains the elements of the HTML page. To refer to a property, you write document.bgcolor, for example.

bgcolor - contains a string with the current background color of the page, ie, "#FF0000" or "white".

fgcolor - contains a string with the current text color.

alinkColor, vlinkColor, linkColor - contain strings with activated link color, visited link color and normal link color respectively.

title - holds the title of the document.

anchors[ ] - array containing the value of all anchors on the page (A NAME tag). Some older browsers do not support it, in which case use links[ ] instead.

links[ ] - array containing the value of all links on the page.

lastModified - contains the date on which the document was last modified. You can use this for automatic "Last Updated on ...." lines.

referrer - contains the URL of the page that led to this one. Useful for researching whose site a user has come from.

forms[ ] - array containing all the forms on the page. See the next article for further information on form objects.

images[ ] - array containing all images on the page. See also image Object below.

applets[ ] - array containing all Java applets on the page.

clear() - method which clears the contents of the current window, maybe in readiness for you to write more on it.

write(HTML tags) - method which outputs HTML tags to the current document. Its parameter is a string containing the HTML, ie,

document.write("

Hello

")

onLoad - event you can use with the <BODY> tag, which will execute any code while the page is loading.

onUnload - another BODY tag event, this executes code when the user leaves the current page.

history Object

The history object represents the browser's history list.

current - contains the value of the current URL.

length - the current length of the history list.

back() - method which moves the user back one.

forward() - method which moves the user forward one.

go(string or number) - moves the user to a specific place in the history list. You can specify a string, ie, "index.htm", or a number. For example, -1 will move the user back one, while 3 will move the user forward three. Due to security reasons, you can't actually get the value of the URLs in the history list.

image Object

All images on the page have the properties of the image object. To test for it, you can use the following code:

if (document.images) {
// put image object code here
}
else {
// put code for older browsers here
}

src - contains the filename of the image. Use this to dynamically change images, such as in a flashy menu system.

border, height, hspace, lowsrc, name, vspace, width - correspond to their relevant parameters in the IMG tag.

complete - contains a Boolean value which describes whether the image has finished loading.

location Object

The location object contains information about the current URL.

href - contains a string of the URL of the current page.

host - contains only the server name (ie, http://www.someISP.com) and special port, if any(ie, www.someISP.com:80).

pathname - contains only the path to the document (ie, "~myspace/index.html").

search - some search forms can produce a URL followed by a search parameter (ie, index.html?searchdata). This property contains the question mark and the information after it, and might be useful if you were creating a search engine or directory for your site. To get at the information without the question mark, assign

location.search.substring(1)

to a variable.

Math Object

The math object contains methods and properties which can be used to manipulate numerical variables.

LN10, LN2, PI, SQRT1_2, SQRT2 - properties which contain log 10, log 2, pi, the square root of 1/2, and the square root of 2 respectively.

abs(x) - the absolute value of x.

acos(x), asin(x), atan(x) - the arc cosine, arc sine and arc tangent of x.

cos(x), sin(x), tan(x) - the cosine, sine and tangent of x.

exp(x) - ex.

log(x) - the natural log of x.

max(x, y) - returns either x or y, depending on which is greater.

min(x, y) - same as above but depends on which is smaller.

pow(x, y) - xy.

round(x) - rounds x to the nearest whole number.

random() - returns a random number between 0 and 1. This can then be multiplied by the number of possible choices you could have, ie, if you were writing a program for automatically choosing your National Lottery numbers, you could write

var number1 = math.round(math.random() * 49)

sqrt(x) - the square root of x.

This covers most of the objects available in JavaScript. However, some very important objects that we will look at in the next article are the form object and form element objects.

navigator Object

The navigator object contains information about the browser being used, so it is useful if you have both a Netscape and an Internet Explorer page.

appName - the name of the browser, will be either "Netscape" or "Microsoft Internet Explorer" or maybe something completely different.

appVersion - important if you want to write code specific to MSIE4. Contains the version number and platform of the browser. Netscape 4 may give "4.0 (Win95;I)" and MSIE will give a convoluted string saying that it's compatible to a certain version of Netscape. Therefore, if you're searching for a specific version, you may have to manipulate the results of this property using the string object (see below).

javaEnabled() - method which returns either true or false depending on whether the browser has enabled Java applets.

plugins[ ] - array containing information about the plug-ins installed on the browser. Unsupported by MS Internet Explorer.

string Object

Any string variable or value can be manipulated using the string object's properties and methods.

length - how many characters are contained in the string.

big(), blink(), bold(), italics(), small(), sub(), strike(), sup() - methods which add the relevant HTML tags to the string. For example, if var variable = "Welcome", then variable.big() would give you "<BIG>WelcomeBIG>".

fontColor(color), fontSize(size) - same sort of thing, but you specify the color or size you want.

charAt(position) - returns the character at the position you specify in the string. For example, if your variable contained "Welcome", then variable.charAt(0) would contain "W", and variable.charAt(5) would contain "m".

indexOf(searchstring, from) - searches for an occurrence of searchstring in the current string. The second parameter, from, is optional - you can specify an index from which to search from. Returns the position of the first letter of searchstring(if found).

lastIndexOf(searchstring, from) - same as indexOf but searches backwards.

substring(pos1, pos2) - returns the string starting from position pos1 to position pos2 in the current string. For example, if variable = "Welcome", then variable.substring(3, 5) = "com".

window Object

The window object contains everything in the browser window, so every other object is a descendant of this one. However you don't have to include "window." in any object names in JavaScript.

status - the text in the status bar. This can be changed, ie,

window.status = "Welcome"

Press this button to see an example:

defaultStatus - the default text that appears in the status bar, ie, "Done" or "Document:done".

frames[ ] - array containing all frames, stored in the order they were defined in the FRAMESET command. Each frame is a sub-window of the main window, and so contains the same properties and methods (except for status, defaultStatus and name). Frames can prove very useful in JavaScript, because you can pass on any variables from one frame to another while the first frame changes location (normally this would wipe all JavaScript code and variables).

For example, imagine that you have two frames, frame1 and frame2, within a main document. If the main document (the one with the FRAMESET) contains a function called function1(), then either frame can access this function by referring to parent.function1(). Similarly, if frame1 contains a variable var1, and you want this to be stored in frame2, you can use code such as:

var2 = parent.frame1.var1

frames.length - the number of frames in the frames array.

parent - if this is a frame, refers to the parent window. You can run functions defined in the parent document by using parent.functionName(), for example.

top - the parent of parents, this is the document which contains all frames.

opener - if this is a pop-up window, refers to the window which opened it. You can run functions defined in the opener window by using opener.functionName(). Although this is not supported by older browsers, you can create your own using the following code:

myWindow = window.open('mypage.htm', 'targetName');
if (myWindow.opener == null) myWindow.opener = self;

name - the name, if any, of the popup window.

alert("message") - method which brings up a warning dialog box with the message you type in.Example:

confirm("message") - method which brings up a dialog box with OK and Cancel buttons and the message you type in. Returns a true if the user clicks on OK, or a false if the user clicks Cancel. Example:

prompt("message") - method which brings up a prompt box, asking the user to type in something, with the message you type in. Returns what the user typed in. Example:

scroll(x, y) - scrolls the window to the co-ordinates x, y.

open("URL", "windowName", "featureList") - method which opens a pop-up window with the URL specified. The window is assigned a name if specified. You can also add certain parameters such as width, height and scrolling. An example:

window.open("popup.htm", "popupWindow", "width=300,height=300")

setTimeout("actions", time) - method which creates a time delay for however long you specify (in thousandths of a second) before running the code or function you specify in "actions". For example,

setTimeOut("changeColor()", 2000)

would run the function changeColor() after a 2 second delay.

No comments: