Tutorial 2 - Objects, Events & FunctionsTutorial 1 - Basic Display - Tutorial 3 - Core Language JavaScript uses modern object oriented programming techniques to make it easier to program and reuse code. JavaScript is also highly interactive because it is event driven (ie. it reacts to user or system activities). This tutorial describes JavaScript objects, function calls and event handling as well as many useful event functions. Objects, Properties and MethodsObjects are collections of related properties and methods. Properties are things, similar to variables but their contents are contained within the object itself. Methods are actions that can be performed on an object. Often methods alter one or more of an object's properties. Note: an analogy may be of help here. One can consider cars as objects. They have a collection of properties, one of which is the status of the parking brakes (park_brake) (either set or released). One method or action would be to apply the parking brakes (apply_park_brake()) which would change the status of park_brake to set. Objects can be created when necessary by using the new operator keyword and equating them to a name. The created object can then have its properties accessed and appropriate methods applied to it. An example of object creation using our analogy is would be: myCar=new Car;// creates one car from the Car template Object properties and methods are accessed using dot notation such as object_name.object_property or object_name.object_method(). Note that methods are identified by brackets. When a method is unambiguous (ie only available through one object), the object_name can be omitted such as alert() instead of window.alert(). But this is not good programming practice. Also the dot notation is considered as a hierarchy (or tree) notation. For example to refer to the current value property of a specific control object within a specific form object you would use a format like form_name.control_name.value. A simple example using the math object's property PI reveals JavaScript's value of π. window.alert('The value of PI is ' + Math.PI);
Another simple math example demonstrates a method that rounds a number to the closest integer. window.alert('The value is ' + Math.round(4.56789));
The JavaScript Appendix shows how object rich the JavaScript language is. There are many core and client side browser specific objects with methods or routines to handle data gathering and display, string and math manipulation, and system calls. The object properties are used to retain settings for recall. User Defined FunctionsFunctions gather a group of statements together for performing a complex operation or reaction to an event action. The general format of a function looks like: function doIt(param1, param2, etc.) {
some statement ;
another statement;
etc;
return xyz;
}
A function is begun with the keyword function followed by a unique identifier name and a set of round brackets. Inside the round brackets is a parameter list of identifiers or names for each value passed to the function, separated by commas. These values can be simple data (such as numbers or strings) or objects. The parameter list can also be empty (ie. null)! Statements within the function are grouped into a block using brace (curly) brackets. A function is called or started by referring to it in another portion of the script or from an event handler. Parameters are passed by value, ie. changing the variables value inside the function will not change its value outside the function. It is good programming practice to use different parameter names when writing a function! Functions can optionally return a single value back to the event handler or other function that called them. Note #1: There is no semicolon after a curly bracket!
Note #2: The round brackets must be used in both the function and the calling statement even when no parameter values are passed. Functions are useful in separating code from the HTML (functions are normally found in head section) and can also be referenced or reused from several other points in the script. Functions are NOT a part of object oriented programming but provide an much easier approach to fast program development. JavaScript makes this tradeoff to keep the language from being 'elitist' only! function biggest(a,b,c) {
biggun=a; // start by assuming first is biggest
if (b>biggun) {biggun=b;}
if (c>biggun) {biggun=c;}
return biggun;
}
...
alert('biggest is ' + biggest(x,y,z));
This function has three formal parameters. Based on the values fed in, the largest numerical is selected and returned to the caller. The caller simply displays the result. Note that the parameter names in the caller do not need to be (and in fact it is good programming practice that they are not) the same as the formal parameters used in the function. Event Handler Function CallsEvents are actions that occur because of user interaction. Using the car analogy given above one possible event is pressing the parking brake pedal which would use the apply_parking_brake() method and perhaps others such as turn_parking_indicator_on() and turn_running_lights_off(). In computing, user events (like moving the mouse) or system effects (like a file completing loading) are common occurrences. JavaScript can use event handlers to initiate some process such as checking for valid information in a form by calling a function. To see the list of possible actions that you can program for by using event handlers, check Appendix - Events and Handlers. The most common method of calling a function using an event handler is to treat the event as an HTML attribute for the appropriate element. Note that any element, not just form controls can have associated events. To enable event handling from an HTML attribute use a call such as: event_name="function_name(parameter_list);return true;"
This format forces a true result to be passed to the event_name.
event_name="return function_name(parameter_list);"
This format allows a function to return a true/false indicator.
This can be used with validation handlers to react to bad input.
event_name="function_name(parameter_list);"
The result passed is unpredictable.
For example: <body onLoad="startUpStuff()>" The preceding line would call the function startUpStuff() as soon as the page was loaded. Another example is: <form name="formx" action="?" method="post"> <input id="b1" name="b1" type="button" value="Transfer Now!" onclick="transfer(a,b);return true" /> ... </form> Note that the string between the quotes is a list of Javascript statements. If there are more than a couple of statements it is better programming practice to call a single function whose task is to sequence those statements. And the code is much more readable too! Event handlers can also be defined within JavaScript itself. For example resizing a window may require repositioning some elements. window.onResize = someFunctionName; In this example someFunctionName will be called on each resizing event. Note that there is no parameter brackets for the function! User's Time On Page ExampleThe next example illustrates how one can time how long a viewer remains on a page. The person_in function records the start time. The person_out function records the stop time, takes the difference and shows the result to the reader. The result could also be accumulated in a cookie! <script type="text/javascript">
function person_in() {
enter=new Date;
}
function person_out() {
exit=new Date;
time_dif=(exit.getTime()-enter.getTime())/1000;
time_dif=Math.round(time_dif);
alert("You've only been on this page for: "+time_dif+" seconds!!");
}
</script>
. . .
<body onLoad="person_in()" onUnLoad="person_out()">
<h1>Timing This Page Now!</h1>
Page Timeout ExampleThis example watches how long the page has been displayed and transfers to another page when timed out. The application is perfect for a static splash screen or front 'intro' page. Be sure to use the onLoad event to initialize the timer function. <script type="text/javascript">
limit=5;// time limit in seconds
limit=limit * 1000;
function timer() {
setTimeout('window.location="http://home.cogeco.ca/~ve3ll/"',limit);
}
</script>
Mouse Rollover EffectIn the most common form, a rollover consists of an image serving as a hypertext link. While the mouse pointer is over the image, it changes appearance to attract attention to the link. For example, you could add a glow effect, a drop shadow or simply change the background color. The onMouseOver and onMouseOut events are used for rollovers. Images are preloaded to avoid delays in transmission.Here is an example of the JavaScript functions which can be placed in the document head section or saved as a separate .js file: // preload images to avoid delays
img1out=new Image;img1out.src="images/enter1.gif";
img1over=new Image;img1over.src="images/enter2.gif";
img2out=new Image;img2out.src="images/keio.gif";
img2over=new Image;img2over.src="images/inria.gif";
// add statement pair for each rollover wanted
function chgImg(el, image) {document.image[el].src=eval(image+".src");}
And the HTML document code to be used for each rollover area is: <a href="/" onMouseOver='chgImg("item1", "img1over")'
onMouseOut='chgImg("item1", "img1out")'>
<img id="item1" src="images/enter1.gif" alt="*" /></a>
and here is what it looks like ... NOTE: These images were created using a freeware painting tool by adding a hot wax effect and then a drop shadow to the text. You can find advice and royalty free clip art on the Web by using a search engine.
Note: Make sure that all of the images are the same width and height. An alternative is to add width and height attributes to the img element to ensure the images are all shown at the same size. Banner Ad CyclerIf your website has several sponsors, then you can use an image link that cycles through each of the sponsors banner ad in turn. The first step is to create an image for each of your sponsors banner ad. All the images should have the same size. The corresponding URLs for the images and for the websites are then loaded into the arrays named adImages and adURLs defined at the start of the script. The img element for the link should be initialized to the first image in the array. The cycle is started by using the onLoad event on the body element. The delay between ads is set by the setTimeout() method. <script type="text/javascript">
adImages=new Array("images/mit.gif", "images/inria.gif", "images/keio.gif");
adURLs=new Array("www.lcs.mit.edu", "www.inria.fr", "www.keio.ac.jp");
thisAd=0;
function gotoAd() {document.location.href="http://" + adURLs[thisAd];}
function cycleAds() {
if (++thisAd==adImages.length) {thisAd=0;} //move to next ad
document.images.adBanner.src=adImages[thisAd]; //display current ad
setTimeout("cycleAds()", 3000); //change ad every 3 seconds
}
</script>
The above is placed in the head section and the following in the body: <body onLoad="cycleAds()"> ... <a href="javascript:gotoAd()"><img name="adBanner" src="images/mit.gif" border="0" alt="Our sponsors"></a> Our Sponsors: The banner ad cycling concept could be extended to present a slideshow to viewers. A form could be set up for control of timing and start/stop functions. Images ViewPortA viewport is a image viewer that allows selection by hovering a related menu item. It is set up much like the rollover effect and the rotating ad banner but this time the event initiators are onmouseover and onmouseout. The onclick event will take you to an appropriate page if programmed. Viewport.zip gives a working example that can be tailored with css and script to fit your needs. Be sure to consult the readme.txt file for setup information. |