Week 13 Notes: JavaScript (Ch 12.3 & 4)Table of contents :
Introduction to JavaScriptToday, virtually every major website uses JavaScript, also called ECMAScript, to enhance the functionality of HTML pages. Image-switching buttons, e-commerce shopping carts, forms processing functions, even the new Flash and Shockwave movies, require the use of JavaScript programs. To one degree or another, every web designer today MUST be able to use JavaScript, even if it is only to copy and modify someone else's code to use in a new webpage. Because almost every site today uses JavaScript, it is important that YOU possess at least a rudimentary knowledge of JavaScript and the fundamentals of computer programming as they apply to JavaScript. Many of the JavaScript scripts used in today's websites are fairly simple; this is not likely to remain true for long, however, as many cutting-edge technologies (Dynamic HTML, Flash, and others) rely on JavaScript programming to unlock their full potential. Unfortunately, not everyone can really learn to program successfully; if everyone could do it, companies wouldn't pay programmers such huge sums of money. Still, you must learn at least a little JavaScript in order to survive in today's competitive Internet marketplace. In this module, I will endeavor to explain the concepts behind JavaScript and programming in general. This module is not intended to substitute for a full-length programming class; instead, they should introduce you to JavaScript programming concepts enough to get you prepared for more in-depth course work. A full examination of JavaScript is included in CNIT 133 For this class, you are NOT required to write any JavaScript elements from scratch. Much of what you do in Homework 11 is to copy and modify already existing scripts from my Homework 11 Sample Web Pages or from the textbook. We are now, for the most part, leaving behind the world of HTML and entering a more complex, more technical, environment which I will do my best to de-mystify and explain. I will be giving you as much detail as I can without obscuring the meaning of my explanations. This module is intended both as an introduction to programming, and as an explanatory reference for certain key aspects of JavaScript. If you are seriously interested in JavaScript, there is one essential book which you must purchase: "JavaScript: The Definitive Guide" by David Flanagan, O'Reilly and Associates, Publisher. This book is THE JavaScript reference book for programmers, and is both comprehensive and well written; you'll find it an indispensable resource for information about the language. You'll find it very difficult to work in JavaScript without a copy of this book, as JavaScript is both enormous and filled with arcane details. Netscape, the developer of JavaScript, also has technical specification documents on JavaScript available as PDF and HTML files from their website at http://developer.netscape.com/; although be warned that these documents, though illuminating and useful, are long, dense, and technical. Programming Overview: Terms and ConceptsUp to this time, you have programmed solely in HTML and CSS, which are DECLARATIVE languages; they declare what something is (HTML) and what that something is supposed to look like (CSS). If you actually want something specific to happen on a web page (such as opening a new window or processing a form), you will need to use an IMPERATIVE language, a language that says "do this!", a language, in short, like JavaScript. Simple activities in JavaScript, like opening a new window or creating custom status bar messages, require minimal programming expertise; scripts for these sorts of things can be had in any decent JavaScript "cookbook". The purpose of these lectures is to present an overall concept of programming in JavaScript which will give you a foundation, upon which you can build, to permit you to go beyond the simple scripts. In JavaScript, a program, called a FUNCTION, is a collection of lines of text-based code which performs some activity. JavaScript is an "event-driven" programming language, which means that functions in JavaScript are triggered by events. What is an EVENT? An event, in JavaScript, is any user interaction with the computer. Clicking the mouse is an event. Pressing a key on the computer keyboard is an event. Moving the mouse around on the screen is an event. Loading an HTML page in the browser is an event. Any action initiated by the user constitutes an event. You already know what a RESOURCE is: a resource is any piece of digital media, whether text, sound, graphic, animation, form element, or CSS document, among others. Think beyond your current definition of resource. Resources can include individual pieces of code, functions, windows, dialog boxes, scrollbars, interface elements, etc. Almost anything in the computer, anything digital, can potentially be a resource which you may then access and/or manipulate in JavaScript. When you are programming in JavaScript, you will write FUNCTIONS which are triggered by user-initiated EVENTS; these functions will, in their turn, access and manipulate RESOURCES for various purposes. In other words, the user will interact with the computer, triggering a JavaScript program; that program will do something, then use resources to display something for the user to see, hear, or experience (this is called FEEDBACK). You, as the programmer, are designing the feedback for the user, as well as figuring out how the program itself is supposed to work. You have to design every aspect of the user experience or USER INTERFACE, the user interface being that portion of the program which the user will interact with that includes both interface elements (such as buttons and text fields) as well as feedback (such as dialog boxes, screens, sounds, etc). When you are programming in JavaScript, you need to ask yourself what YOU would expect if you were using this device. Would it beep? Would the buttons hilite as you clicked them, and would you want to see rollover effects (like active/inactive button states)? What kind of response would you expect from the computer once the program is finished executing? Would you want to see dialog boxes? Should the HTML page advance to a new page? Should a window open? And what would really IRRITATE you? What do you want to make sure DOESN'T happen? You, as the programmer, must define every aspect, every detail, of the UI (User Interface), including every aspect of how it behaves. But remember that old adage, KISS: "Keep It Simple, Stupid!" Don't include flashy highlights and rollovers that distract from the functionality of the program. A good interface is almost invisible, assisting the user without being obtrusive. Having said all of this, the user interface is, in some respects, merely the clothing on the living creature of your program. The real flesh and bone of a program lies in the calculations, the operations, the decisions being made by the program itself which actually do the task at hand. You can obsess about what your buttons are going to look like, or what your dialog boxes are going to say, until your hair falls out, but if you haven't got code inside of your program deciding something or solving something or calculating something or moving something around, you're not going to have anything useful in the end. Imperative programming languages, such as JavaScript, C/C++, and Java, use something called LOGIC to make simple decisions and perform repetitive actions in a program. In addition, these languages use OPERATIONS to perform mathematical calculations, comparisons, transfers of data, and other activities within the computer itself. In combination, logic and operations do all of the actual work inside of a program. How logic operates, and what sort of operations JavaScript is capable of, are topics for discussion in later sections. All that you have to remember right now is that computers are really very stupid creatures; they can't do anything for themselves unless you tell them how to do it, which means that you have to spell EVERYTHING out for them. In addition, the operations and decisions computers can make are really very simple ones compared to the ones humans can make; sophisticated programs create an ILLUSION of complex behavior by layering many simple operations together and performing them at unbelievably high speeds. At the core of any program, however, are basic logic structures and basic operations which we will introduce in these modules. Computer programming is mostly comprised of problem solving: taking large complex problems, breaking them down into the smallest possible pieces, and building programs out of these simple bits. Whenever students ask me how to tackle a problem, I always respond that they should WRITE DOWN the things that they are sure about, even the stupidest-seeming things. Once you have written down things you KNOW must happen or problems you have already solved, it makes it much clearer what remains to be done. In addition, you must start breaking down your problems into the simplest bits that you can think of, until you have the entire problem broken down into single tasks which the computer can perform. I will attempt to explain a little more about this process in the next module. SummaryIn JavaScript, user-initiated EVENTS trigger JavaScript FUNCTIONS. These functions contain LOGIC which makes decisions or performs repetitions, using OPERATIONS to calculate, to compare, or to solve various problems. Once all logic and operations are finished, the function accesses and/or manipulates RESOURCES to generate user FEEDBACK based on the decisions and operations it has made. Obviously, this is an artificially simplified statement (since logic, operations, resources, and functions would actually be a part of ALL of these processes), but it gives you a GENERAL idea of the process involved in the execution of a JavaScript program. You, as a programmer, will design every aspect of the JavaScript code itself, as well as the USER INTERFACE. You will be taking complex problems, breaking them down into single tasks which the computer can execute, and reassembling these simple bits into larger-scale programs which can then perform the complete task. Variables: An IntroductionA computer stores data, among other things. The term "data" sounds intimidating, but it really isn't. Data is simply information. On the computer, data can be numbers, or words, or pictures, or sounds, or movies, or anything. When you program in any imperative programming language, you will need to instruct the computer when to store data, and when to transfer data, and when to delete data, etc. Data, however, can be much more than mere information; it can also be references to actual elements of the web page or the web browser itself. You'll see what I mean as we go along. In imperative programming languages, such as JavaScript, data is stored in VARIABLES. A variable is really just a container for information, for data. In JavaScript, ANYTHING can be stored in a variable. A number or a word could be stored in a variable. A picture or a sound file could be stored in a variable. Even a reference to an actual browser window or an entire HTML page could be stored in a variable in JavaScript, allowing you to open or close (or otherwise manipulate) that browser window (for instance), or even alter an individual HTML element in that browser window, via the appropriate JavaScript variable. After we have explored some more basic JavaScript programming concepts, I will show you how variables and actual browser elements work together. Until I have given you some more theoretical information about programming, however, none of my explanations of the practical applications would make any sense, so please bear with me. Think of a variable as if it were a box. You take data and you put it into a box (a variable). You can also replace the data in one of these variable boxes with new data. A variable MUST have a name; otherwise, you'll have no way to refer to that variable in a manner which the computer (or YOU) can understand. In JavaScript, names ARE case-sensitive (along with everything else), so SPELLING COUNTS! Variable names follow the standard naming conventions we have discussed in earlier modules, and should usually begin with a lower-case letter. In the following example, I will create a variable called "george". I am going to fill george with a number, the number 1. Here is a conceptual picture of george:
As you can see, george, the variable, is a box with a name, containing the number 1. In JavaScript, you will use variables to store all data, whether it be numbers, or words, or pictures, or whatever. Declaration and InitializationWhen creating variables in an imperative programming language, there is a two-step process: 1) declaration (declaring a variable), and 2) initialization (initializing a variable). Again, these technical words sound intimidating, but they're not. When you DECLARE a variable, you tell the computer that that variable exists; you also tell it what that variable's name is. When you INITIALIZE a variable, you fill that variable with data for the FIRST time (initial = first), setting it to its initial, or beginning, state. Computers are stupid. If you don't tell them that something exists, they can't figure it out for themselves; that's why you have to declare a variable. In JavaScript, you would declare "george" (from the above example) like this: var george; To declare a variable in JavaScript, you must first state the JavaScript keyword, "var" (which tells the computer that you want to create something of type "var" or variable), followed by a space, followed by the name that you want to call that variable (in this case, the name is george); the command is finished off with a semi-colon to end the line of code. Once you have declared a variable, you may refer and make changes to that variable simply by stating its name and performing OPERATIONS upon it. Most operations in JavaScript (including addition (+), subtraction (-), multiplication (*), and division (/), among others) are performed with a handful of symbols, many of which will be already familiar to you; I will talk more about these OPERATORS a little later. In JavaScript, I could initialize the already-declared variable, george, using the following syntax: george = 1; In the above example, I have initialized the variable, george, setting it equal to the number 1; I have done this using the "gets" operator, which is represented by the equals (=) sign. The "gets" operator (=) replaces the contents of whatever is on its left-hand side with whatever is on its right-hand side. In the above example, george "gets" 1; this means that the "gets" operator takes the number 1 from its right-hand side and sticks that value into george on its left-hand side, replacing george's contents; since george has never contained any data, this process INITIALIZES george, setting him to a starting value of 1. Again, I have ended my command, my line of code, with the semi-colon end-of-line marker; every complete command in JavaScript must end its line with a semi-colon. A COMMAND is an instruction or set of instructions for the computer, telling it to do something (or multiple somethings). Every time you come to the end of a command in JavaScript (which will end a line of code), you must mark the end of that line with a semi-colon, as in the above examples. I could also declare and initialize the variable, george, in a single step using the following syntax: var george = 1; First, I declare george to exist by using the var keyword, then I use the "gets" operator to initialize george to contain the number 1. Although it is possible to combine these two processes (declaration and initialization) together into one command as in the above example, it is important for you to understand that these are two separate actions, and that there will be times when you will NEED to separate variable declaration and initialization for one reason or another. A Note on Semi-ColonsJavaScript is derived from the programming language called "C". All C-based languages end lines of code with semi-colons; a semi-colon (;) is the end-of-line or end-of-command marker. You have already seen a similar use of the semi-colon in CSS, where a semi-colon marks the end of a property definition (i.e. Note: Older code written in JavaScript does NOT always use a semi-colon to mark the end of a line of code. Theoretically, JavaScript, under many circumstances, may count carriage-return characters as a replacement for semi-colon characters; this does not always work properly, however. I cannot recommend the omission of semi-colon characters when coding commands in JavaScript, as it opens you up to unexplained errors due (I assume) to bugs in the JavaScript interpreters. Variables: Data TypesAs mentioned earlier, variables can contain many kinds of data or information. There are several official TYPES of data which JavaScript can understand. In brief, I am going to outline a few of the most important of these data types, since I will be referring to them when we start coding a little later. In JavaScript, there are three essential "primitive" data types: numbers, strings, and booleans. Here are some numbers: 10 -147 .0035 1.5 -520.0003 As far as JavaScript is concerned, numbers may be positive or negative, and may have decimal places or be without decimal places. As I mentioned earlier, however, JavaScript is a C-based language; the C-based languages include C++, Java, and JavaScript, among others. In C-based languages, numbers are divided into two separate varieties: integers (int) and floats (float). Integers (int) are whole numbers with NO decimal places. Here are some integers: 1 -100 247 -68000 0 Floats (float) are numbers WITH decimal places. Here are some floats: .0003 146.5 -2.575 10000.1 Again, when you are programming in JavaScript, you will not usually differentiate between integers and floats. However, JavaScript DOES recognize a difference between integers and floats, and it has a few built-in features which allow you to manipulate numbers as either one or the other. STRINGS are collections of alphanumeric characters. Anything you can type on a computer keyboard may potentially be part of a string. Strings, in JavaScript, are always marked with quote marks. Here are some strings: "Hi" "Wow, you have 2.5 children!" "Michael" "Hey, dude, I like your green hair..." As you can see, strings are ALWAYS enclosed in double-quote marks, and may contain a variety of characters, whether text, numbers, spaces, or punctuation. In HTML, you have already dealt with strings frequently. Every time you set an attribute for a tag, you are actually setting that attribute equal to some string value (i.e. Even though strings may have numbers contained within them, there is a distinct difference between string-based numbers and actual numbers. For instance, these two values are NOT the same: 1 "1" The first example is the actual number, 1. The second example is the CHARACTER "1", which is NOT a number; rather, it is merely a symbol that you type on the computer keyboard. You can NOT perform mathematical computations on a STRING "1", whereas you CAN perform mathematical computations on a NUMBER 1. Having said this, JavaScript has on-the-fly conversion capabilities which automatically convert string numerical characters to numbers, as well as numbers to strings, under appropriate conditions. Although this sort of automatic conversion is a tremendous convenience, it does NOT keep variables from being EITHER numbers OR strings at any given time; you will frequently be called upon to differentiate between these two data types in your code. I myself have been tripped up more than once by these on-the-fly conversions while programming in JavaScript, so I just wanted to make sure that I mentioned this feature. The third "primitive" data type in JavaScript is BOOLEAN. Booleans sound very technical, but they are quite simple. Invented by George Bool in a previous century, boolean numbers, in JavaScript and other traditional programming languages, have just two states: false and true, 0 and 1, off and on. The values of false, 0, and off are all equivalent, while the values of true, 1, and on are also equivalent. In JavaScript, booleans will always be either false or true (not off/on or 0/1). Booleans are everywhere in computer-based or electronics-based equipment. Have you ever noticed the | and 0 characters printed on the on/off switches for your computer, stereo, or other pieces of electronics equipment? Those characters represent on and off for the switch, with | or 1 being ON, and 0 being OFF. That's a BOOLEAN! Switches themselves are firmly embedded in the history of the first computers. Once upon a time, computers were just gigantic, room-sized banks of switches, and, later, switches and lightbulbs, which turned on and off mechanically; when a lightbulb or switch was on, that was a 1, whereas when a lightbulb or switch was off, that counted as a 0. Using these 0's and 1's, you could create BINARY code (binary means numbers in base 2, which is all 0's and 1's). Just like the secret codes you may have played with as a child, you could say that the number 0 represents the letter "a", and that the number 1 represents the letter "b", and that the number 10 (10 in binary is 2 in our regular counting system) represents the letter "c", and that the number 11 represents the letter "d", etc. With big enough binary numbers, you could extend your binary "secret code" to represent not only letters, but also colors, or sound waves, or picture information, or whatever you like. Once you have decided which binary numbers represent which characters or sounds or pictures, you could store this binary information in your computer. With the "key" to your binary "secret code", you could then take this binary information out of your computer, manipulate it in some fashion, convert it back into a semblance of its original form, and display, play, or printout this media. Using switches and lightbulbs, of course, computers could only store and manipulate a VERY limited amount of binary information (it took roomfuls of switches just to get enough numbers together to add up your checkbook, let alone represent millions of colors!); those early computers also weren't very fast. Now, with silicon microchips and advanced magnetic memory, computers can store and manipulate mind-boggling quantities of information at magical speeds. All of this data, however, is still encoded, stored, and manipulated in the computer using on/off, binary, BOOLEAN states. Although you will probably never have to get deep enough into the computer to be forced to look at actual binary conversion of data (thank goodness!), JavaScript, naturally enough, is still heavily reliant on booleans and boolean states. You will frequently be testing conditions in code to see whether something is true or false, a boolean state. Has the user clicked on a particular button? That information would be either true (the user HAS clicked on the button) or false (the user has NOT clicked on the button), a boolean state. Has the user visited this page three times? If they HAVE visited the page three times, the condition would be TRUE, whereas if they have visited the page FEWER than three times or MORE than three times, the condition would be FALSE, another boolean state. In some kind of game code, you might have a boolean variable which remains false until the user has collected all of the "magic wands" in the game (for instance), whereupon the boolean variable would be changed to true, allowing new levels of the game to open up. Boolean variables are everywhere in JavaScript. Besides the three "primitive" data types, there is also the OBJECT data type in JavaScript. Objects include a whole host of structures and entities which are beyond the scope of this introductory lecture. In the next section, however, we will discuss the basic features of generic objects, as you will need to know a little bit about objects in order to use JavaScript effectively (since almost everything in JavaScript is built using objects). Beyond the primitive data types, and objects, there are two more data types you should be aware of: null and undefined. The variable that is null contains NO information. You should know, however, that null is NOT 0; Zero (0) is an integer, a number. The null variable is empty. In JavaScript, the null variable is differentiated from the undefined variable. An undefined variable has not been declared, and therefore does not exist, or has not been initialized, and so contains no data. You will find that there are many times when you will need to check for the null or undefined variable data types, especially when handling user feedback or input. For instance, if you program JavaScript to bring up a prompt window (which allows a user to type in some information and click either the OK or Cancel buttons), you will need to test for the undefined or null variable if a user has not given any input or has pressed the "Cancel" button on the prompt dialog box; this is just one place where you might need to test for this data type. The null variable and the undefined variable may be treated interchangeably in JavaScript, but can be detected individually in the most modern browsers, if needed. There are many other data types, but they are beyond the scope of this class. For more information on data types, refer to "JavaScript: The Definitive Guide", Chapter 3. Typed and Untyped Languages and Simple Variable OperationsIn JavaScript, variables may contain ANY type of data. When you declare a variable, you only need to state the keyword var and the name of the variable; this creates a generic variable. Once you have a variable declared, you can stick a number or a string or a boolean or an object into the variable, and change the data type of the variable at will. Example: var george = 1; george = "Hi"; In the above example, I have set george equal to the number 1. In the second line of code, I have replaced the contents of george with a string, "Hi". I have changed george's data type from a number to a string. This kind of action is possible because JavaScript is an "untyped" language. In an untyped language, a variable may be of any data type, and an individual variable's data type may be changed at any time. Most programming languages, like C++ and Java, are "typed" languages. In a typed language, a given variable may only ever be ONE data type. For instance, in Example (C/C++): int george = 1; string fred = "Hi"; float ethel = 1.052; In the above example in C/C++, I have declared and initialized three different variables. The variable george is an integer (int) and may only ever contain an integer. The variable fred is a string, and may only ever contain a string. The variable ethel is a float, and may only ever contain a number with decimal places. In typed languages like C/C++, variable data types remain fixed for the duration of a program. As I mentioned earlier, even though JavaScript is an untyped language, and even though you can change a variable's data type on-the-fly in JavaScript, variables can only be a SINGLE data type at any given time, whether that type be a number, a string, a boolean, an object, or null/undefined. Here are some more JavaScript examples of variables being declared, initialized, and otherwise operated upon: var kate = "hi"; var louie = 10.25; var josie = louie; var sam = 200; var answer = louie + josie + sam; kate = answer; In order of the examples: the variable kate now contains a string value, "hi". The variable louie now contains a number. The variable josie has been set equal to louie, which means that a copy of louie's contents have been placed inside of josie; both josie and louie, then, are equal to 10.25. The variable sam now contains a number as well. The variable called answer has been set to the sum of louie and josie and sam, which would be 10.25 + 10.25 + 200, or the number 220.5. Note: answer is just a random name, picked because it makes sense in English; I could have named it anything. The variable kate (which has already been declared), then, has had its string content of "hi" replaced with the numerical content of the variable answer, which changes kate's data type from a string to a number. The following example is WRONG: louie + josie + sam = answer; Even though the above example looks like math operations that you might perform on paper, the above syntax is backwards. The variable answer needs to contain the sum of louie + josie + sam, which is only possible if the variable answer is on the LEFT-HAND side of the "gets" (=) operator (since the "gets" operator always replaces the contents of the left-hand variable with whatever is on the right-hand side). Left-to-right orientation, then, is important in JavaScript, as well as case-sensitivity! Example (CORRECT): var answer = louie + josie + sam; The following example is ALSO WRONG: var answer = louie + JOSIE + Sam; Earlier, I initialized the variables josie and sam using all lower-case letters in their names. Since JavaScript is case-sensitive, JOSIE and Sam represent different, non-existent, undefined variables. The variable answer in the above example, then, would end up containing non-valid information, producing a bug and a JavaScript error in your code. Again, I apologize for the abstractness of these examples, but you must understand the basics of JavaScript variable syntax before you can do anything at all with the language. I hope that you can see, though, that handling these variables and performing simple mathematical operations upon them is fairly straightforward as long as you understand the basic logic behind their syntax. Of course, you can do a lot more than mathematical operations with JavaScript; we'll get to a few simple, practical things before the end of this module. JavaScript Objects and Functions: An OverviewBecause JavaScript is an object-oriented programming language, I need to tell you a little bit about JavaScript "objects" and the structure of the language generally, before we can actually start programming in JavaScript specifically. In any programming language, you write lines of code which are executed, left-to-right, top-to-bottom, just like in HTML. In an object-oriented programming language such as JavaScript, however, much of this code is organized in OBJECTS. In fact, most of the built-in features of JavaScript use objects of one sort or another, which means that you need to understand basic object syntax before you can do much of anything, including reading the JavaScript reference books. In an HTML page in a JavaScript-enabled web browser, most or even all things on the page are mirrored in JavaScript objects. There is a window object which refers to the browser window itself, there is a document object which refers to the HTML page itself (and, potentially, everything contained in that HTML page), there is an images object which has to do with pictures, etc. By manipulating these objects in JavaScript code, you can affect the behavior and appearance of an HTML page, call up dialog boxes or other resources, and invoke a fairly sophisticated set of commands to do your bidding. Every object in JavaScript has two main components: a set of PROPERTIES, and a set of METHODS. Properties are generally passive in nature, describing the state of some feature of the object. Methods, on the other hand, are generally active, performing some sort of task. Over the years, I have used something called the "object-oriented car", a common metaphor in programming instruction, to explain object-oriented programming principles. As I have grown more sophisticated in my explanations, however, the "car" object example has begun to break down. Now, instead of describing the entire car in my lectures, I describe only the STEERING WHEEL of the car using object-oriented programming terms. Let us create a SteeringWheel object (and notice how the name of the object has NO SPACES!). This SteeringWheel object has one property, "direction", and one method, "honk()".
The direction property of the SteeringWheel object says what direction the SteeringWheel is pointed. Since this is a VERY simple SteeringWheel, only left, right, or center would be legal values for this property. The honk() method of the SteeringWheel object honks the car's horn; we'll talk more about this method later on. The code that defines the SteeringWheel object, with all of its properties and methods, is called a CONSTRUCTOR. The exact syntax for creating your own object constructor is really beyond the scope of this introductory lecture. However, you WILL be invoking pre-built constructors when you use JavaScript, so we'll talk about how to do this. The SteeringWheel constructor merely defines the basic structure of the SteeringWheel object; it does NOT actually create a SteeringWheel which you can manipulate directly. To get a SteeringWheel object that you can use, you need to create an INSTANCE of the SteeringWheel object (also known as INSTANTIATING a SteeringWheel object). When you create an instance of an object, you are creating ONE copy of the object which you have control over. In JavaScript, you will need to instantiate an object by using a variable to contain a copy of the object. First, you'll declare a variable to hold the instance of the SteeringWheel object; then you'll initialize the variable as a "new" SteeringWheel object using the "new" keyword. Example: var theWheel = new SteeringWheel(); Whenever you instantiate an object, you MUST use the keyword, new, before the call to the object constructor, as you see above. Also, notice the opening/closing parentheses characters following the call to the SteeringWheel constructor (and prior to the semi-colon end-of-line marker); these parentheses are called the "function call" operator (which calls/invokes a function), and are an essential part of the object instantiation process. A FUNCTION, in JavaScript, is a collection of lines of code, a program, which does something (like switch an image, or pop up a new window, or BUILD AN OBJECT, etc). In order to execute a function, to make a function "run" in JavaScript, you must state the name of the function, followed by the "function call" operator (the opening/closing parentheses characters); this will cause the function to execute when your code is executed. Note: we'll talk about making our OWN functions a little later on in this module. It turns out that an object constructor, such as the SteeringWheel object constructor in the above example, is made in JavaScript out of a FUNCTION. The same function syntax that you will use to create miniature programs later on is also used to make object constructors! Just as a side note, it turns out that FUNCTIONS are also OBJECTS themselves; this is because almost everything in JavaScript is built out of objects. I'm sure that this seems confusing now, but don't worry about it; as you get deeper into JavaScript, over time, it will all start to make much more sense to you. Here's the code again: var theWheel = new SteeringWheel(); Whenever you instantiate an object, you will DECLARE a variable, then INITIALIZE that variable to be a NEW instance of whatever OBJECT CONSTRUCTOR you want. An object constructor is really a FUNCTION, which you must execute in order to create your object; this is done by stating the name of the object constructor function (in this case, SteeringWheel), followed by the function call operator (the parentheses characters). Again, the function call operator is necessary in order to execute the object constructor function. As in all lines of code in JavaScript, you must end the line with a semi-colon end-of-line marker. Once you have created an instance of your desired object, you may access the PROPERTIES and METHODS of the object by using DOT SYNTAX. Dot syntax is a way of accessing child elements of a parent object (remember parents and children?) by using period/dot (.) characters between parent and child elements to indicate a path through a complex tree of relationships, much as the slash (/) character is used in URL syntax to indicate a path through a complex directory structure on a web server. Here's a much simpler example. If I wanted to put $10.00 cash into an empty cash register in my local coffee house in Guerneville, CA, USA, using JavaScript dot syntax to indicate the path to the cash register, the line of JavaScript code might look something like this: earth.northAmerica.usa.california.sonomaCounty.guerneville.cinnabarCoffee.cashRegister = 10; Dot syntax always creates a path from the most general to the most specific element, reading from left-to-right, and, as you can see from the above example, there are NO SPACES IN THE NAMES of the elements or between the dots! Back to the instance of our SteeringWheel object, theWheel: The SteeringWheel object has one property, direction. Object properties can be accessed via the instance of the object using dot syntax. In the following examples, I am assuming that theWheel has already been declared and instantiated. Example: theWheel.direction = "left"; In the above example, I have set the direction property of theWheel object equal to the string, "left". Surprise! An object property is really a VARIABLE which is attached to a particular object; this property may be filled with whatever data we like (in this case, a string). Having executed the above line of code, theWheel is now pointed towards the left. Example: theWheel.direction = "right"; Now, theWheel is pointed towards the right. Note: At this point, students often point out to me that a property is supposed to be static, yet the direction property of theWheel seems to be turning the steering wheel of the car rather than merely reflecting which direction theWheel is pointing! Well, oftentimes object properties are not as static as I have led you to believe (remember, I said "usually" static!). In a real JavaScript object, however, I would probably have written a method called "turnWheel()" which actually turned the wheel, and the direction property would merely have been a string which indicated the current direction of the wheel. Please cut me some slack, I'm trying to make a simple example here! Now, if I wanted to honk the horn of theWheel, I would need to call the honk() method of theWheel. A METHOD is really a FUNCTION which is attached to an object, just as a PROPERTY is really a VARIABLE attached to an object (again, a function is a program which performs some action)! Therefore, I use the function call operator (opening/closing parentheses) after the name of the method (and dot syntax, of course). Example: theWheel.honk(); The above example executes the honk() method of theWheel, causing theWheel's horn to honk. Example (complete code): var theWheel = new SteeringWheel(); theWheel.direction = "left"; theWheel.direction = "right"; theWheel.honk(); Boy, if we drove like this down the road, we'd probably get a ticket for reckless driving! You can create more than one instance of an object, simply by declaring and instantiating more copies of the object. Example: var theWheel = new SteeringWheel(); var theSecondWheel = new SteeringWheel(); theWheel.direction = "left"; theSecondWheel.direction = "center"; theWheel.honk(); In the above example, there are two copies of the SteeringWheel object (hopefully attached to two separate cars!). The direction property of theWheel is set to "left", while the direction property of theSecondWheel is set to "center". Then, I honked the horn of theWheel, but I left theSecondWheel silent. Each instance of an object is separate, and contains separate information. Even though both objects in the above example are SteeringWheel objects, they are completely independant from one another! I can make as many instances of an object as I want, but I think TWO SteeringWheel objects is enough for now... JavaScript Objects and Functions: Part TwoLet's look at a REAL example of JavaScript objects in action. In this example, I am going to instanciate two Image objects, which are used to represent GIF/JPEG pictures for use on a web page. I am then going to set the src (source) properties of the Image objects to appropriate URLs; these src properties are identical to the SRC attribute of an IMG tag. Example: var picture0 = new Image(); var picture1 = new Image(); picture0.src = "capitalA.gif"; picture1.src = "capitalB.gif"; Now, let's say that I have an IMG tag named "fred" on my web page. Example: <img src="capitalD.gif" width="54" height="54" name="fred"> I could access the image, fred, on my web page using something called the "simplified document object model", which allows me to use dot syntax to point to an element on an HTML page. Example (abbreviated): window.document.fred Example (abbreviated; looking at SRC attribute of fred): window.document.fred.src Example (full line of code): window.document.fred.src = picture0.src; window is the instance of the Window object which represents the current web browser window. document is the instance of the Document object which represents the current HTML page in the web browser window. fred is the name of the IMG tag on the HTML page. src is the SRC attribute of the fred IMG tag. In the above example, I am setting the src property for fred equal to the src property of the picture0 Image object, thus changing fred's picture from a graphic of the letter D to a graphic of the letter A! I've just performed an image switch! Hooray! Now, I'm going to switch fred's image to picture1, the graphic of the capital letter B: window.document.fred.src = picture1.src; Woowee! I've switched that image again! I'm programming in JavaScript, doing something useful! Wow! Alright, so this is not ALL the code that you'll need to deal with image switching, but it outlines the basic principles. First, you instanciate image objects with src properties set to URLs for the images that you want. Then, you refer to the named IMG tag on the page using dot syntax and the simplified document object model, and reset the src property of the named IMG tag equal to the src property of the desired instance of the Image object. Almost every web site in creation uses image switching to make rollover effects on graphical hyper-references! Be warned, however: all images involved in a switch MUST have the same dimensions, the same width and height! The SteeringWheel Object RevisitedWe need to talk more about the honk() method of the SteeringWheel object, to illustrate additional basic JavaScript programming principles. Our computerized car horn is capable of doing more than merely honking; it can play tunes, as well! There are two tunes it can make, along with the generic honk sound: Beethoven's Fifth Symphony Theme, and Mary Had a Little Lamb. Here are the string values representing these car horn tunes: "5th" for Beethoven's Fifth Symphony (dah dah dah DAAAAHHHH!). Now, I need to pass these string values into the horn() method of the SteeringWheel object. To do this, I need to place the desired string BETWEEN the parentheses of the function call operator for the horn method in my JavaScript command. When you do this, you are said to be "passing a parameter" or "passing an argument" to the method. Example: theWheel.horn("5th");
In the above example, I am passing the string value "5th" as an ARGUMENT or PARAMETER (these words are often used interchangeably here) to the horn method of theWheel. This causes the horn in theWheel to play Beethoven's Fifth rather than the standard honking sound. Note: everything I say about parameters and arguments in this section may ALSO be applied to functions, since methods are really functions attached to an object! Let's have the horn play Mary Had a Little Lamb. Example: theWheel.horn("MHALL");
Ah, what a sweet sound! By passing different arguments to a method, I can cause that method to behave in different ways. In JavaScript generally, you will pass ARGUMENTS or PARAMETERS for many different reasons and to many different effects. You can pass any data type you like as an argument to a method, whether it be number or string or boolean or whatever. Each built-in JavaScript method will require different sorts of arguments, and will perform different kinds of actions. Example: theWheel.horn(false); I passed the boolean value, false, to the horn method. The way the horn method is written, a false value passed as an argument prevents the horn from honking. Many methods can accept boolean values of true or false in this way. Many methods are programmed to accept more than one argument. If you wish to pass more than one argument to a method, you must separate each argument with a comma (and an optional space, if you wish). Example: theWheel.horn("5th", "MHALL");
In the above example, the horn method first plays Beethoven's Fifth, then plays Mary Had a Little Lamb. Example: theWheel.horn("honk", "5th", "MHALL", "honk");
In the above example, the horn method plays a sequence of sounds, starting with a honk, moving to Beethoven's Fifth, then Mary Had a Little Lamb, and ending with another honk. In JavaScript, methods may accept one or more arguments, or a changeable number of arguments, depending upon how that method is written. Let's look again at our real world example, using the Image object. Example: var picture0 = new Image(54, 54); It turns out that the Image object constructor can accept TWO arguments, both integers. The first argument represents the WIDTH of the image in pixels, while the second argument represents the HEIGHT of the image in pixels. These arguments initialize the width and height properties of the instance of the Image object in question. Example: var picture0 = new Image(54, 100); var myWidth = picture0.width; var myHeight = picture0.height; The variable myWidth is now equal to 54, which is the value of the width property of picture0. The variable myHeight is now equal to 100, which is the value of the height property of picture0. One Last Note on VariablesVariables are boxes for information. By stating a variable name in JavaScript code, you are passing or manipulating the information contained in that variable. Remember this example from a previous section? var louie = 10.25; var josie = louie; By stating louie's name in the second line of code above, I was able to copy or pass the information from louie into josie by using the "gets" operator. In the same way, I can pass information from a variable into a method by stating the name of the variable between the parentheses of the function call operator. Example: var myHornSound = "5th"; var theWheel = new SteeringWheel(); theWheel.horn(myHornSound); I just love to hear Beethoven's Fifth Symphony! Example: var myHornSound0 = "5th"; var myHornSound1 = "MHALL"; var theWheel = new SteeringWheel(); theWheel.horn(myHornSound1, myHornSound0, "honk"); In the above example, I passed THREE arguments to the horn method of theWheel; two of the arguments were variable names, and one was an actual string with no variable involved. Some of my arguments can be variables, while others of my arguments can be direct data; this is perfectly legal. The following example is NOT legal: var myHornSound = "5th";
var theWheel = new SteeringWheel();
theWheel.horn("myHornSound");
Notice how I passed the STRING "myHornSound" to the horn method when I REALLY wanted to pass the variable named myHornSound? SummaryA VARIABLE may hold an INSTANCE of an OBJECT. Each object has PROPERTIES and METHODS. Properties are essentially variables attached to an object, while methods are essentially FUNCTIONS attached to an object. A FUNCTION is a program which performs some action. Whenever you wish to execute a function (or a method), you must state the name of the function, followed by the FUNCTION CALL OPERATOR (which is represented by opening and closing parentheses characters). Properties and methods of an object are accessed using DOT SYNTAX, which allows you to trace the path of relationships between parent and child objects. Note: as you might expect, then, properties and methods of an object are child elements of the object. When you execute a method or function, you may pass ARGUMENTS or PARAMETERS to that method or function. Arguments/parameters passed to a method/function can influence the behavior of that method/function in some fashion. Data may be passed as an argument to a method/function either directly (by stating the actual number, string, or boolean value), or by passing a variable containing the data (by stating the variable name). Event Handlers and the javascript Absolute URLJavaScript is an event-driven programming language, where JavaScript commands are triggered by events caused by user interaction. JavaScript uses special EVENT HANDLERS inserted as ATTRIBUTES into ordinary HTML tags to access user events, such as clicking the mouse. Here is the event handler which deals with mouse clicks: onClick As long as we are supporting Netscape 4.x browsers, most event handlers MUST be placed into tags which can ordinarily accept mouse events, such as the A (anchor) tag, or the INPUT tag in a FORM. Here is the onClick event handler inserted into a hyper-reference: <a href="#" onClick="var george = 1;">Link Word</a> The value of the onClick event handler attribute would be a JavaScript command of some sort. More than one command may be placed into an event handler in this fashion simply by appending commands onto the end of the previous command (don't forget your semi-colon end-of-line markers after each command!). Example: <a href="#" onClick="var george = 1; var fred = 2; var answer = george + fred;">Link Word</a> Before we get any deeper into this material, we need to look at the JavaScript Window object, which is built into every JavaScript-enabled web browser. The Window ObjectWhen you open a JavaScript-enabled web browser, such as Netscape Communicator or Internet Explorer, certain built-in objects in JavaScript are declared and initialized automatically. One of these built-in objects is an instance of the Window object called window (with a lower-case "w"). Again, you do NOT need to declare the window instance of the Window object; this is done for you automatically when a web browser window is opened. The window instance refers to the current browser window, and has many properties and methods associated with it. A complete list of properties and methods of the Window object are printed in "JavaScript: The Definitive Guide", if you are interested. For the moment, I am only concerned with the alert() method of the Window object. The alert() method of the Window object causes an alert dialog box to open. Here is an example of the alert() method in action: The alert() method REQUIRES one argument, a string, which will become the text displayed in the alert dialog box. Technically, the alert() method is invoked with the following complete syntax: window.alert("Hi");
Because everything on an HTML page is displayed within the web browser window, however, it is NOT necessary to state the window instance name directly; window is automatically implied as the parent object for everything on an HTML page. It is perfectly safe to state the alert() method by itself, without using dot syntax to explicitly state the parent/child relationship between it and the window instance. The following syntax for calling the alert() method is perfectly safe and correct: alert("Hi");
Here is an example of the alert() method placed into an onClick event handler: <a href="#" onClick="alert('Hi');">Link Word</a>
Although in the previous examples, the string value passed as the argument to the alert() method was enclosed in DOUBLE-quotes, you can see that I have marked the string value in the above example using SINGLE-quote marks. I believe that we have encountered this problem in previous modules. Attributes may NOT have double-quote marks inside of the double-quote marks beginning and ending the value for the attribute, as this will break your HTML code. Because we NEED quote-marks of some kind to delimit the string value inside the function call operator for the alert method, we MUST use single-quote marks within the bounds of the double-quote marks marking the attribute value. When we write commands within ordinary JavaScript scripts, however, we will be able to go back to using double-quote marks to delineate string values; we'll talk about this later. Again, the following example would be WRONG: <a href="#" onClick="alert("Hi");">Link Word</a>
Those extra double-quote marks are EVIL. Corrected Example: <a href="#" onClick="alert('Hi');">Link Word</a>
You don't have to use the onClick event handler from within an A (anchor) tag. Instead, you can use the javascript absolute URL as the value for the HREF attribute in order to trigger JavaScript commands. Example: <a href="javascript:alert('Hi');">Link Word</a>
In the above example, I have stated the SCHEME for the absolute URL (javascript), followed by the colon character, followed by the "scheme_specific_part", the actual JavaScript command desired. Note: When using the javascript absolute URL, you must NEVER have any spaces in your JavaScript code; otherwise, the javascript URL will fail to operate. The following example is WRONG because there are spaces in the URL: <a href="javascript:var fred = 1; alert(fred);">Link Word</a> If your JavaScript command requires spaces (as in the above example), you MUST then use the onClick event handler rather than the javascript absolute URL. As I mentioned earlier, you do NOT have to put your onClick event handlers ONLY in A (anchor) tags; you may place the onClick event handler in ANY clickable tag, such as the INPUT tag in a form. Example: <form>
<input type="button" value="Alert Me" onClick="alert('Hi There');" />
</form>
Displayed: The SCRIPT TagIt must be evident to you now that event handlers (such as onClick) are inadequate for holding any substantive quantity of code. Most JavaScript code in a JavaScript-enhanced HTML page is placed within a SCRIPT tag. The main SCRIPT tag for a page goes in the HEAD of your HTML document. Between the opening and closing SCRIPT tags, you will write out your lines of JavaScript code. The SCRIPT tag has ONE attribute, TYPE. The TYPE attribute tells the browser which programming language is being coded inside of the SCRIPT tag. There are many different languages that can be coded within a SCRIPT tag; there are even several different versions of JavaScript itself. For this introductory class, all that you are concerned with is the main version of JavaScript. Tag: Example (abbreviated): <script type="text/javascript">
// Here's a couple of lines of JavaScript code:
var george = 1;
alert("Howdy");
</script>
Example (in context): <html>
<head>
<title>Sample JavaScript Page</title>
<script type="text/javascript">
// Here's a couple of lines of JavaScript code:
var george = 1;
alert("Howdy");
</script>
</head>
<body>
<p>Some content...</p>
</body>
</html>
In the above example, I have placed my SCRIPT tag in the HEAD of my HTML document. Between the opening and closing SCRIPT tags, I have programmed my JavaScript code, creating a variable called george containing a numerical value of 1, and calling the alert() method which is receiving one argument, the string "Howdy". Notice how I am able to use DOUBLE-QUOTE marks again to mark my string values? This is possible because I am NOT inside an attribute (as I was with onClick). Remember in our CSS module, when I talked about CSS comments? Single line comments were marked at the beginning of the line with "//", while multiple line comments were marked "/* comment... */". JavaScript, and all of the C-based languages, use the SAME commenting style! Unlike CSS, however, single line comment syntax IS supported in JavaScript, so you may use it with impunity here (as I did immediately following my opening SCRIPT tag). As with CSS, I will also need to place HTML comments inside my opening and closing SCRIPT tags, to hide the JavaScript code from non-JavaScript-enabled web browsers. Example: <script type="text/javascript">
<!--
// Here's a couple of lines of JavaScript code:
var george = 1;
alert("Howdy");
//-->
</script>
There is an older, deprecated attribute of the SCRIPT tag: LANGUAGE. You will still see many JavaScript-enhanced web pages using the LANGUAGE attribute of the SCRIPT tag rather than the TYPE attribute. Example: <script language="javascript">
<!--
// Here's a couple of lines of JavaScript code:
var george = 1;
alert("Howdy");
//-->
</script>
It is no longer necessary to use the LANGUAGE attribute. As an HTML page loads, the SCRIPT tag is executed, declaring and initializing variables, and executing methods. Example Code (abbreviated): <script type="text/javascript">
<!--
var george = 1;
alert("Howdy");
alert(george);
//-->
</script>
Example Code (in context): <html>
<head>
<title>Sample JavaScript Page</title>
<script type="text/javascript">
<!--
var george = 1;
alert("Howdy");
alert(george);
//-->
</script>
</head>
<body>
<p>Some content...</p>
</body>
</html>
In the above example, I first declare and initialize a variable, george. I then call the alert method, passing the string value "Howdy" as an argument to the alert method. Last, I call the alert method again, passing the contents of the variable, george, to the alert method. Note: even though the contents of george are a NUMBER, not a STRING, JavaScript automatically converts the number INTO a string for use by the alert method. Cool, huh? Here is the above example displayed. Notice how the alert dialog boxes pop up as the page loads in the above example? As I said, the code inside the SCRIPT tag is executed as the HTML page loads. Of course, you're not usually going to want to have EVERYTHING in your script tag execute all at once; that would be complete chaos. To reserve some actions, and to call those actions at will rather than just as the page loads, requires the use of a FUNCTION. We'll talk about functions in the next section. Final NotesAn HTML page may, in fact, have several SCRIPT tags on it, both in the HEAD and in the BODY of the document. Because SCRIPT tags are executed as an HTML page loads, you may have a SCRIPT tag in the BODY of a page which lays on-the-fly HTML (built from JavaScript code) into the BODY of the HTML page as the page is parsing. The ramifications of this topic are outside the scope of this introductory lecture, but this sort of JavaScript usage is VERY common. JavaScript code may ALSO be coded into an external text file, called a ".js" file, which is very much like an external ".css" document, only filled with JavaScript code rather than CSS code. A ".js" file, or even several ".js" files, would be attached to an HTML page using the SCRIPT tag, and many HTML pages could share the same ".js" files. For more information, see "JavaScript: The Definitive Guide", section 12.2.2, pp.215-216. Basic Function SyntaxInside a SCRIPT tag, you may define as many FUNCTIONs as you wish. A function is a piece of executable code, a program. A function can be triggered either by a call from an event handler, set in motion by a user, or by a call from another function. A function requires the following syntax: function doStuff() { };
First, you must state the JavaScript keyword, function, which tells the JavaScript interpreter that you want to create a FUNCTION. This is followed by a space, then the NAME of the function, followed by the parentheses characters (which are NOT, strangely, the function call operator here, but, rather, serve another purpose which we'll talk about a little later). The parentheses are followed by another space, then the opening and closing curly-braces we used in CSS; this is all ended, of course, with a semi-colon end-of-line marker. This statement of a function is called a FUNCTION DECLARATION. Note: the semi-colon end-of-line marker at the end of a function declaration is RARELY, or NEVER, seen, and is usually omitted entirely. Example (correct): function doStuff() { }
Between the curly-braces, then, we can define lines of code. In fact, just as in CSS, we will break out our lines of code, putting the opening and closing curly-braces on separate lines, and each line of JavaScript code between them on separate lines. Example: function doStuff() {
var george = 1;
alert(george);
}
Again, this function would be placed inside of a SCRIPT tag. You may define as many functions as you like inside of your SCRIPT tag. Example: <script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
White Space in JavaScriptYou will notice in the above examples that I have indented the lines of JavaScript code inside of the function declaration; this is a customary practice, and, unlike with HTML, it is supported and perfectly legal. Indent child elements (inside of curly-braces) one tab in from parent elements. As you can see in the above example, I have also used white space to separate my functions. This practice, too, is customary, supported, and legal. The one thing you have to beware of is placing CARRIAGE RETURN characters anywhere but at the ends of lines of code (or as blank lines). JavaScript can potentially interpret carriage return characters as SEMI-COLON end-of-line markers; if you put a carriage return in the middle of a command, the code may break. Example (WRONG): function doStuff() {
alert(
"Howdy"
);
}
As you can see in the above example, I have placed illegal carriage returns in the middle of my function call operator, the parentheses. This will cause my code to break. Example (CORRECTED): function doStuff() {
alert("Howdy");
}
Calling a Function from an Event HandlerOnce I have declared and defined my functions, I can call those functions from the event handlers or javascript absolute URLs in the BODY of my HTML page. Example (abbreviated): <a href="#" onClick="doStuff();">Link One</a> <a href="javascript:doSomethingElse();">Link Two</a> Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff();">Link One</a></p>
<p><a href="javascript:doSomethingElse();">Link Two</a></p>
</body>
</html>
Here is the above example displayed. In the above example, do you notice how the code remains inactive UNTIL you click on the hyper-references in the BODY? When the user interacts with an HTML element, a function is called (from either an event handler or from the javascript absolute URL) and executed. Organizing our JavaScript code inside functions in the SCRIPT tag allows us to keep our HTML code relatively brief and uncluttered. It also opens up a door to a lot of power which is outside of the scope of this introduction to explore. I will mention again, however, that a function may be called from within ANOTHER function. Example (abbreviated): <script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
doSomethingElse();
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
doSomethingElse();
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
</head>
<body>
<p><a href="javascript:doStuff();">Link One</a></p>
</body>
</html>
Here is the above example displayed Notice how I only called the doStuff() function from within my event handler? The doStuff() function has been rewritten to call the doSomethingElse() function. So, from one event, I can call a function which can call many functions! I know that this doesn't seem like such a big deal to you right now, but it provides a means of writing the most sophisticated and powerful code imaginable. I can call both built-in JavaScript methods (such as the alert() method of the window object), and functions which I have defined myself! Pretty slick! Basic Function SyntaxInside a SCRIPT tag, you may define as many FUNCTIONs as you wish. A function is a piece of executable code, a program. A function can be triggered either by a call from an event handler, set in motion by a user, or by a call from another function. A function requires the following syntax: function doStuff() { };
First, you must state the JavaScript keyword, function, which tells the JavaScript interpreter that you want to create a FUNCTION. This is followed by a space, then the NAME of the function, followed by the parentheses characters (which are NOT, strangely, the function call operator here, but, rather, serve another purpose which we'll talk about a little later). The parentheses are followed by another space, then the opening and closing curly-braces we used in CSS; this is all ended, of course, with a semi-colon end-of-line marker. This statement of a function is called a FUNCTION DECLARATION. Note: the semi-colon end-of-line marker at the end of a function declaration is RARELY, or NEVER, seen, and is usually omitted entirely. Example (correct): function doStuff() { }
Between the curly-braces, then, we can define lines of code. In fact, just as in CSS, we will break out our lines of code, putting the opening and closing curly-braces on separate lines, and each line of JavaScript code between them on separate lines. Example: function doStuff() {
var george = 1;
alert(george);
}
Again, this function would be placed inside of a SCRIPT tag. You may define as many functions as you like inside of your SCRIPT tag. Example: <script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
White Space in JavaScriptYou will notice in the above examples that I have indented the lines of JavaScript code inside of the function declaration; this is a customary practice, and, unlike with HTML, it is supported and perfectly legal. Indent child elements (inside of curly-braces) one tab in from parent elements. As you can see in the above example, I have also used white space to separate my functions. This practice, too, is customary, supported, and legal. The one thing you have to beware of is placing CARRIAGE RETURN characters anywhere but at the ends of lines of code (or as blank lines). JavaScript can potentially interpret carriage return characters as SEMI-COLON end-of-line markers; if you put a carriage return in the middle of a command, the code may break. Example (WRONG): function doStuff() {
alert(
"Howdy"
);
}
As you can see in the above example, I have placed illegal carriage returns in the middle of my function call operator, the parentheses. This will cause my code to break. Example (CORRECTED): function doStuff() {
alert("Howdy");
}
Calling a Function from an Event HandlerOnce I have declared and defined my functions, I can call those functions from the event handlers or javascript absolute URLs in the BODY of my HTML page. Example (abbreviated): <a href="#" onClick="doStuff();">Link One</a> <a href="javascript:doSomethingElse();">Link Two</a> Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff();">Link One</a></p>
<p><a href="javascript:doSomethingElse();">Link Two</a></p>
</body>
</html>
Here is the above example displayed. In the above example, do you notice how the code remains inactive UNTIL you click on the hyper-references in the BODY? When the user interacts with an HTML element, a function is called (from either an event handler or from the javascript absolute URL) and executed. Organizing our JavaScript code inside functions in the SCRIPT tag allows us to keep our HTML code relatively brief and uncluttered. It also opens up a door to a lot of power which is outside of the scope of this introduction to explore. I will mention again, however, that a function may be called from within ANOTHER function. Example (abbreviated): <script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
doSomethingElse();
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff() {
var george = 1;
alert(george);
doSomethingElse();
}
function doSomethingElse() {
alert("Howdy");
}
//-->
</script>
</head>
<body>
<p><a href="javascript:doStuff();">Link One</a></p>
</body>
</html>
Here is the above example displayed. Notice how I only called the doStuff() function from within my event handler? The doStuff() function has been rewritten to call the doSomethingElse() function. So, from one event, I can call a function which can call many functions! I know that this doesn't seem like such a big deal to you right now, but it provides a means of writing the most sophisticated and powerful code imaginable. I can call both built-in JavaScript methods (such as the alert() method of the window object), and functions which I have defined myself! Pretty slick! Variables: Local and GlobalVariables come in two flavors: local and global. Local variables are temporary. A local variable is declared, initialized, and used for a short period of time, then thrown away. A local variable in JavaScript can only be used within a single function; no other functions have access to that particular variable; when a function is finished executing, the local variables for that function are thrown away. Global variables are persistent. A global variable is created when your web page is loaded, can be accessed by many different processes and functions, and lasts until your web page is unloaded from the browser window. Again, global variables last for the duration of your web page or program; local variables are used by one process or function, then thrown away. The distinction between local and global variables is very important in JavaScript programming. We will not have time to explore all of the ramifications of local and global variables in this brief introduction. However, I will be referring to local and global variables frequently in the upcoming sections. Global variables in JavaScript are declared at the base level of the SCRIPT tag. Example: <script type="text/javascript"> <!-- var george = 1; var fred = "Hi"; //--> </script> In the above example, both george and fred are GLOBAL variables because they have been declared at the base level of the SCRIPT tag. Global variables can be accessed within all functions. Example (abbreviated): <script type="text/javascript">
<!--
var george = 1;
var fred = "Hi";
function doStuff() {
alert(george);
}
function doSomethingElse() {
alert(fred);
}
//-->
</script>
Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
var george = 1;
var fred = "Hi";
function doStuff() {
alert(george);
}
function doSomethingElse() {
alert(fred);
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff();">Calling doStuff()</a></p>
<p><a href="javascript:doSomethingElse();">Calling doSomethingElse()</a></p>
</body>
</html>
Here is the above example displayed. I can also change the contents of (or operate upon or manipulate) global variables from within functions. Example (abbreviated): <script type="text/javascript">
<!--
var george = 1;
var fred = "Hi";
function doStuff() {
alert(george);
george = "Boo";
fred = "Howl";
}
function doSomethingElse() {
alert(fred);
george = "Yum";
fred = "Delicious!";
}
//-->
</script>
Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
var george = 1;
var fred = "Hi";
function doStuff() {
alert(george);
george = "Boo";
fred = "Howl";
}
function doSomethingElse() {
alert(fred);
george = "Yum";
fred = "Delicious!";
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff();">Calling doStuff()</a></p>
<p><a href="javascript:doSomethingElse();">Calling doSomethingElse()</a></p>
</body>
</html>
Here is the above example displayed. As you can see, each time we call one of the functions, we are changing the contents of the global variables. Local variables are declared WITHIN a function declaration ONLY. Local variables will last only as long as the function is executing. When the function has finished executing, its local variables are thrown away. Functions may NOT access the local variables of other functions. Example (abbreviated): <script type="text/javascript">
<!--
function doStuff() {
var george = "Wow";
alert(george);
}
function doSomethingElse() {
var fred = "How about that!";
alert(fred);
}
//-->
</script>
In the above example, the variable george is a local variable of doStuff(), while the variable fred is a local variable of doSomethingElse(). Because fred and george are local variables in different functions, I can not access fred from doStuff(), nor can I access george from doSomethingElse(); either of these actions would result in a JavaScript error. Example (INCORRECT): <script type="text/javascript">
<!--
function doStuff() {
var george = "Wow";
alert(fred);
}
function doSomethingElse() {
var fred = "How about that!";
alert(george);
}
//-->
</script>
In the above INCORRECT example, I am trying to access george from doSomethingElse() and fred from doStuff(), neither of which are possible actions. Example (POSSIBLE): <script type="text/javascript">
<!--
function doStuff() {
var george = "Wow";
var fred = "How about that!";
alert(george);
alert(fred);
}
//-->
</script>
In the above example, george and fred are both local variables of the SAME function; any process within that function, then, could access either george and/or fred. We'll talk more about handling local variables in the next sections. One Final NoteEach function may contain local variables which have the SAME names as local variables contained in other functions. For instance, the following code is perfectly CORRECT: function doStuff() {
var myNumber = 1;
alert(myNumber);
}
function doSomethingElse() {
var myNumber = 10;
alert(myNumber);
}
Because local variables are temporary, only existing for the duration of a given function, other functions may use the SAME local variable names. The technical reason for this is called PROTECTED NAMESPACE, which we don't need to go into here. Suffice it to say, that each function is like a separate universe, with its own collection of local variables, and that these local variables are separated or protected from the local variables in other functions. So, even though I am referring to the local variable myNumber in BOTH doStuff() and doSomethingElse(), these two variables, because they are both LOCAL variables, have NO relationship to one another whatsoever. Local and Global Variable Naming ConventionsOfficially, it doesn't matter what you name local and global variables, as long as you follow the naming conventions that we have discussed in earlier modules. In practice, however, there are standardized local and global variable naming conventions that many programmers follow. Here is the naming convention that I follow: Local variable names always begin with the prefix "my". Example: myText myCounter myPosition myNumber Global variable names always begin with the prefix "the". Example: theText theCounter thePosition theNumber Following a local/global naming convention, like the one outlined above, can really help you keep your local and global variables straight when you start writing more complex code. Trust me, it makes a difference! I also strongly recommend making your variable names reflect their purpose; this will make your code read much more like regular English than like techno-gibberish. For instance, if your variable is holding the result of a calculation, name it myResult or myAnswer rather than goobah or fred. Which of the following code examples is easier to read? var goobah = 1 + 1; var myAnswer = 1 + 1; If I were dealing with temporary information, I might call my variable temp or myTemp. If I were dealing with some HTML text, I might call my variable myHTMLText or myText or theText (depending on whether it were local or global). In the same way, if I were writing a function which switched images, I would name that function using verb syntax, reflecting its purpose: switchImage() or handleImageSwitch(), rather than grumble() or snuffBox(). I had one student who named all of her functions after days of the week, and all of her variables after friends. Needless to say, she couldn't remember which function did what, or what the variables were for. Another person had the bright idea of naming a utility function "fillUpMyCokePlease()". Again, no one can ever remember exactly WHAT that function is supposed to do! You get the idea. Do yourself a favor: name variables and functions after their purpose, not after your dog or to commemorate the purchase of your new lava lamp. You'll thank yourself later, trust me... Functions: Declaring ArgumentsYou have already passed arguments to a built-in JavaScript method, the alert() method of the window instance of the Window object. Example: alert("Howdy");
Example (conservative syntax): window.alert("Howdy");
As mentioned earlier, methods are functions which are attached to objects. Functions, then, can receive arguments. Now that you know how to code a function, I can show you how to declare arguments for your functions. Example: <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff() {
alert("Howdy");
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff('Boo');">Calling doStuff()</a></p>
</body>
</html>
In the above example, I have declared one function, doStuff(). In the BODY of my page, I have called doStuff() from the onClick event handler in the hyper-reference; I am passing doStuff one argument, the string "Boo". Now, how would I access that argument inside of the doStuff() function, and how could I pass the argument's data to the alert() method call in doStuff()? The easiest way to access an argument inside a function (and the only one we're going to explore in this introductory lecture) is to declare a local variable which will hold the argument data; this local variable MUST be declared within the parentheses characters following the name of the function, doStuff, in the function declaration. Note: You would NOT use the keyword, var, when declaring this type of local "argument" variable. Example (abbreviated): function doStuff(fred) {
// some code here...
}
By declaring the local variable, fred, within the parentheses of the function declaration in the manner shown above, I am creating a container to hold the argument value being passed into the function. Within the function, then, I could access the local variable, fred, normally. Whatever argument has been passed to this doStuff function would be accessed via fred. Example (abbreviated): function doStuff(fred) {
alert(fred);
}
Now, in the above example, what value does fred actually contain, and what string would display in the alert dialog box? The answer is, it depends on what value has been passed as an argument to the doStuff function. Example: <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff(fred) {
alert(fred);
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff('Boo');">Calling doStuff()</a></p>
<p><a href="#" onClick="doStuff('Ouch');">Calling doStuff() Again</a></p>
</body>
</html>
Here is the above example displayed. When the first link calls the doStuff function from its onClick event handler, it passes one argument to doStuff(), the string "Boo". That string value is passed into the local variable, fred, because fred has been declared as a local "argument" variable within the parentheses of the doStuff function declaration. The variable fred now contains the string value "Boo", which is passed to the alert() method in the above code; the alert() method then causes an alert dialog box to pop up which says "Boo". The second link performs the same actions, only passing the string "Ouch" instead of "Boo". As you can see, both hyper-references call the SAME function, but each hyper-reference passes that function a different argument value. The function itself always performs the same tasks, but its behavior is altered slightly depending on the value of the argument passed into the local variable, fred. This is the seed of how you create generalized functions to perform variations on the same task! Without these sorts of local argument variables, a function would be forced to behave identically EVERY time you called it, just like the functions you saw in the previous sections. WITH these local "argument" variables, a function becomes much more flexible in the tasks it can perform. Just as I can pass more than one argument to a method/function, I can create more than one local "argument" variable by declaring those variables within the parentheses of the function declaration. Each of the local variable names declared between the parentheses of the function declaration would be separated by a comma. Example (abbreviated): function doStuff(fred, george) {
alert(fred);
alert(george);
}
Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff(fred, george) {
alert(fred);
alert(george);
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff('Boo', 'Scared You!');">Calling doStuff()</a></p>
<p><a href="#" onClick="doStuff('Ouch', 'That Hurt!');">Calling doStuff() Again</a></p>
</body>
</html>
Here is the above example displayed. Arguments are always passed into the local "argument" variables for a function in sequence from left to right. The first argument passed to the above function would be passed into the first local argument variable, fred, and the second argument passed to the above function would be passed into the second local argument variable, george. The local "argument" variable name is irrelevant to which argument gets passed into which variable; the arguments are always passed into the function in order, left to right. Being able to declare local variables to hold arguments for a function is an extremely powerful tool. Obviously, we haven't time to explore all of the ramifications of this capability, but I'll try to show you something simple but practical to do with this power in the next section. Opening a New WindowIn this section, I'm going to write a function which throws up an alert dialog box, then opens a new browser window. To do this, I am going to call two methods of the window instance of the Window object: alert() (which you already know) and open() (which opens a new browser window). A call to the open() method is usually written out like this: window.open(); Even though the reference to the window object is understood implicitly, the conservative syntax given above looks much more like regular English, and is always used. The open() method requires three arguments, all strings. The first argument is the URL (absolute or relative) that will appear in the new window. The second argument is the NAME of the new window (which will NOT be visible to the user, but rather identifies the window in JavaScript). The third argument is a series of parameters, describing the appearance of the new window; this third argument may NOT contain any spaces, nor will it contain any additional quotation marks. Here is an example call to the open() method: window.open("http://www.yahoo.com/", "marian", "width=300,height=200"); Here is a link which demonstrates this code in action. Note: you MUST close this new window when you have finished looking at it; don't just hide it behind the current browser window, or some of my later code examples will not operate correctly. Notice how the new window in the above example had NO status bar, NO location bar, possibly even NO menubar or scrollbars; it wasn't resizable, either. The window was 300 pixels wide and 200 pixels high, and nothing else, because that was all I defined in the third argument of the open() method. To get a new browser window with more features, I have to state ALL of the features that I want, explicitly, in the third argument. Again, each of these features MUST be separated with a comma within the third argument string, and there must be NO SPACES anywhere or it won't work; this is NOT HTML, it just resembles it, so beware. A complete list of all of the window features available with the window.open() method is printed in "JavaScript: The Definitive Guide", pp.731-734. Because these features are not pertinent to my demonstration, I am not going to go into all of them here. Here is a full-featured window called from JavaScript: window.open("http://www.yahoo.com/", "marian", Here is a link which demonstrates this code in action. Note: again, you MUST close this new window when you have finished looking at it; don't just hide it behind the current browser window, or some of my later code examples will not operate correctly. Now that I've talked about the window.open() method, let's add that method to our function declaration. Example: function doStuff() {
alert("Here is Yahoo!");
window.open("http://www.yahoo.com", "marian", "width=300,height=200");
}
Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff() {
alert("Here is Yahoo!");
window.open("http://www.yahoo.com", "marian", "width=300,height=200");
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff();">Calling doStuff()</a></p>
</body>
</html>
Here is the above example displayed. Again, PLEASE CLOSE THE NEW WINDOW when you have finished with it! Obviously, if we hard-coded everything into our functions, we would have to write a different function for each message in the alert dialog box and each URL in the new window. This is an example of someplace where you would want to create a GENERALIZED function by declaring ARGUMENTS for the function (as we discussed previously). Example: function doStuff(myMSG, myURL) {
alert(myMSG);
window.open(myURL, "marian", "width=300,height=200");
}
By creating a generalized function as I have in the example above, I can now simply pass arguments to doStuff, passing the string in myMSG to the alert() method, while passing the string in myURL to the window.open() method. Example (in context): <html>
<head>
<title>Sample JavaScript</title>
<script type="text/javascript">
<!--
function doStuff(myMSG, myURL) {
alert(myMSG);
window.open(myURL, "marian", "width=300,height=200");
}
//-->
</script>
</head>
<body>
<p><a href="#" onClick="doStuff('Here is Yahoo', 'http://www.yahoo.com/');">Yahoo Link</a></p>
<p><a href="#" onClick="doStuff('Here is Macromedia', 'http://www.macromedia.com/');">Macromedia Link</a></p>
</body>
</html>
Here is the above example displayed. I can call this new generalized function from as many places as I wish. Again, there is NO correlation between what sort of information I pass into an argument variable, and the name of that variable; arguments are always passed into a function from left to right, the first argument going into the first variable, the second argument going into the second variable, etc. The order of the arguments being passed into a function, then, is critical. Variable names are also important, but mostly to help you, as the programmer, understand what the code is doing. To prevent confusion, the names of the local argument variables should be utilitarian, simple, and clear, which will make your code more comprehensible, as well as easier to read. Simple Debugging Techniques for JavaScriptYou are going to run frequently into JavaScript code that doesn't work. In fact, MOST code fails to operate correctly the first time you test it, for one reason or another. If you are testing your code in Netscape Communicator, there is something called the JavaScript console which will give you information about what the mistakes in your JavaScript code actually are. Netscape 6 browsers have the JavaScript console available directly from the Communicator menu. Netscape 4.x browsers require that you replace the URL in the location bar of your browser with the following code, then press the return/enter key: javascript: The JavaScript console will give you some information about your JavaScript errors, some of it helpful, some of it obscure. Clear the console after EVERY visit; that will make it clearer to you how many errors you actually have on your next visit, since otherwise the console will just build up a history of ALL of your errors. It is outside the scope of this introductory lesson to go into very much detail regarding debugging techniques. Here is a list of some of the most common errors that students make: Spelling: JavaScript is CASE-SENSITIVE. Check your spellings! Incorrectly-placed Carriage Returns: Students often place carriage returns in the middle of parentheses for methods or functions, which usually doesn't work. Spaces: Names may have NO SPACES in them. Some arguments may also not have spaces in them, depending on the method in question. Don't forget to follow the naming conventions that I outlined in the earlier modules! Missing Quote Marks: One quote mark missing, and your JavaScript program will fail. The same holds true for missing parentheses or curly-braces, etc. I get caught by this myself surprisingly often. There is one easy technique that you can use to debug code when something doesn't work: add a call to the alert() method into a sequence of lines of code. Test your code, and see if the alert dialog box you inserted shows up or not. Remove that alert(), and put another one someplace else. Keep testing with the alert() method in various locations until you pinpoint the precise point in the code where everything breaks down. Debugging code is almost an art form, and requires a good deal of experience. The few techniques I've outlined here, however, should help you to get started. The biggest secret to debugging code is NOT to let yourself get frustrated. Mistakes and bugs in code are NORMAL, and you should ALWAYS expect them. If code works right the first time, it's usually a fluke and a cause for celebration; I dance around the house, patting myself on the back, on the rare occasions when that happens! Methodical coding procedures are also of paramount importance. Once you've gotten a grasp of what good coding form is all about, you will need to develop certain habits, producing code in a very regular and regimented fashion. Again, I can't go into details here, but I've given you a lot of hints throughout this entire online course, both in HTML, in CSS, and in JavaScript, which can be applied to ANY coding that you do. Good luck! Common Event HandlersJavaScript has a long list of event handlers which it understands. Some of the most commonly used event handlers are:
onClick onMouseOver onMouseOut onChange onLoad In addition to these common ones, there are two less common but conceptually important event handlers I feel should also be mentioned: onFocus onBlur Again, event handlers would be added to an HTML tag, and would be triggered upon that event occuring to the tag. In order to support Netscape 4.x browsers, most event handlers must be placed within clickable tags, such as A (anchor) and INPUT. onClick we've already discussed, so I won't repeat myself here. The onMouseOver event occurs when a user passes their mouse over an element. Example:
<a href="#" onMouseOver="alert('Hi');">onMouseOver Event</a>
Displayed: The onMouseOut event occurs when a user passes their mouse AWAY from an element.
Example:
<a href="#" onMouseOut="alert('Bye');">onMouseOut Event</a>
Displayed: The onMouseOver and onMouseOut events are usually used to trigger image switches and custom status bar messages; we'll talk about custom status bar messages a little later in this module.
The onChange event handler is triggered when an element changes its state. The onChange event handler is most commonly used with form elements, such as the SELECT tag pulldown menu.
Example:
<form>
<select name="testPulldown" onChange="alert('You changed me');">
<option value="1">First Choice</option>
<option value="2">Second Choice</option>
<option value="3">Third Choice</option>
</select>
</form>
Displayed: This sort of JavaScript-enhanced interface element is most commonly used for navigational purposes on a web site; we'll talk about that, as well, a little later in this module. The onLoad event handler has to do with the loading of HTML pages into a browser window. When a page is completely loaded, when all of its graphics and text and sound files and movies are fully downloaded, the onLoad event is triggered. The onLoad event handler ALWAYS goes in the BODY tag of the HTML page. I am not going to demonstrate this one here; its true purpose is beyond the scope of this class. All I will say is that the onLoad event handler is most commonly used to trigger initialization functions for an HTML page. The onFocus and onBlur event handlers are mostly connected with form elements, and are not commonly used. However, the concepts of FOCUS and BLUR are extremely important, so I thought I should mention them. When you SELECT something on the computer, you are giving that thing FOCUS. When you DESELECT something, you are giving it BLUR. Here is a text field: OperatorsThere are operators, and there are operands. Example: 1 + 1 The plus (+) sign is an OPERATOR, because it performs some action. The 1's are OPERANDS, because they are the things being acted, or operated, upon. You already know several JavaScript operators:
Here are some more operators, called COMPARISON operators, which you are probably also familiar with:
You have already encountered the "gets" (=) operator, also called the "assignment" operator. As you know, this operator is NOT used for comparisons; rather, it takes whatever is on its right side, and places that information into whatever is on its left side. Example: var george = 1; To make comparisons for equality, you need to use the EQUALITY operator, which is represented by two equals signs together:
If you want to test whether something is NOT equal, you would use the INEQUALITY operator, which is represented by an exclamation point and an equals sign together:
Example: if (theSky == "gray") putOnYourOvercoat(); If the sky is gray, put on your overcoat. Example: if (theWater != "warm") turnOnTheHotWater(); If the water is not warm, turn on the hot water. Both of the above JavaScript examples use something called BRANCH logic; we'll talk more about JavaScript logic in the next section. I would also like to point out that I have created variable and function names which reflect PURPOSE, and, when used, sound very much like an English sentence; you should strive for this sort of clarity when writing JavaScript code. Here are some more operators: Logical AND:
Logical OR:
Example: if (theSky == "blue" && theTemperature >= 65) takeOffYourCoatAndTakeAWalkOutside(); If the sky is blue AND the temperature is greater than or equal to 65 degrees Fahrenheit, take off your coat and take a walk outside. The condition above will only be met if BOTH the sky is blue AND the temperature is greater than or equal to 65; otherwise, nothing will happen. Example: if (theSky == "gray" || theRain == "falling") stayHomeWithABook(); If the sky is gray OR the rain is falling, stay home with a book. The condition above will be met if EITHER the sky is gray OR the rain is falling, which allows you more potential opportunities to stay home with a good book. Again, I'll discuss JavaScript branch logic syntax in more detail in the next section. JavaScript also provides something called the INCREMENT and DECREMENT operators, which either add or subtract 1 from something.
Example: var myCounter = 0; myCounter++; // myCounter is now equal to 1. myCounter--; // myCounter is now equal to 0. myCounter--; // myCounter is now equal to -1. Without the increment and decrement operators, we would be forced to say: var myCounter = 0; myCounter = myCounter + 1; // myCounter is now equal to 1. myCounter = myCounter - 1; // myCounter is now equal to 0. myCounter = myCounter - 1; // myCounter is now equal to -1. The increment and decrement counters provide a shorthand for adding 1 to a variable or subtracting 1 from a variable. This is extremely useful when counting mechanical repetitions using LOOP logic, another form of JavaScript logic which we will introduce in the next section. The last operator we will discuss is called the "assignment with addition" operator, or the "add by value" operator.
This is another shorthand operator, like the increment/decrement operators. If we say "a += b", it is the same as saying "a = a + b". With the "by value" or "assignment with operation" operators, you get two actions for the price of one! The first operation is performed between the two operands, then the result of that operation is put into the first operand, leaving the second (right-hand) operand unchanged. Example: var fred = 1; var ethel = 2; fred += ethel; In the above example, the variable fred starts out equal to 1, and the variable ethel starts out equal to 2. After the "add by value" operator works on the two variables, fred is now equal to 3, while ethel is still equal to 2. Again, this is because: fred += ethel; is the same as saying: fred = fred + ethel; This operator is VERY important in JavaScript because it is used to CONCATENATE, or join, strings together. You'll need to do this in order to create HTML text on-the-fly using JavaScript. Example: var myName = "Michael"; var myText = "<p>Hi there, "; myText += myName; myText += "! How nice to see you!</p>"; In the above example, I am using the "add by value" operator to concatenate my HTML string together, adding in the user name stored in the variable myName, to create one whole paragraph of HTML code. If this were a real piece of JavaScript code, I would probably have gotten the user's name from a prompt or out of a form text INPUT field, and stored that information, placing it into HTML pages (using SCRIPT tags and the document.write() method) at key points to personalize the site for the user. There are a lot of other operators, but these are most (though not all) of the essential ones. For more information about operators, see "JavaScript: The Definitive Guide", Chapter 5. Summary of Operators
Logic: A Simplified OverviewComputer logic is an entire topic unto itself, which is really beyond the scope of this class. However, I wanted, at least, to INTRODUCE some of the concepts regarding computer logic to you before we went any further. Computer logic is not like human logic, it's really more of a routing process, or a mechanization process. In fact, it is comprised of only TWO forms in JavaScript: BRANCH logic, and LOOP logic. Branch LogicBranch logic allows for simple decisions to be made, based on a CONDITION. A condition can be anything, and is TESTED, returning a value of either true or false (a boolean!). For example, let's say the CONDITION that I am testing is the color of the sky. Depending on what color the sky is, I am going to take off my hat, or put on my overcoat, or take out my umbrella. IF the sky is blue, then I am going to take off my hat. IF the sky is gray, then I am putting on my overcoat. IF the sky is dark gray OR black, then I am taking out my umbrella. I am about to go out of the house, and have come to a decision point. Depending upon the color of the sky, I am going to take different actions. My path, at this point, will BRANCH, depending upon the condition that I am testing (in this case, the color of the sky). This is an example of branching logic: I come to a decision point, and my path may BRANCH in any number of different ways, depending upon the result of the condition test that I am making. In JavaScript, this sort of logic is expressed using an IF STATEMENT. Example: if (theSky == "blue") takeOffMyHat(); First, I state the keyword, if, which makes this an IF STATEMENT, followed by a space. Then I put opening and closing parentheses characters; these parentheses characters are NOT, in this case, a function call operator, but a container for the CONDITION that I am testing. If whatever is being tested inside the parentheses is true, then I will perform whatever action follows the parentheses; if whatever is being tested inside the parentheses is false, then I will go on to the next line of JavaScript code, ignoring the statement following the parentheses. I may perform MULTIPLE lines of code if my condition is true by using curly-brace characters to define space, much as I do with the function declaration. Example: if (theSky == "blue") {
takeOffMyHat();
openTheWindowCurtains();
waveToTheNeighbors();
};
Unlike a function declaration, it is customary to place a semi-colon end-of-line marker at the end of the curly-braces of an if statement. If I want to BRANCH my decision point, I can use the ELSE statement in combination with the IF statement. Example: if (theSky == "blue") {
takeOffMyHat();
} else {
putOnMyGaloshes();
};
The else statement provides a "catch-all" action for anything which does not meet the first condition. Notice how I have NOT placed a semi-colon after the first set of curly-braces and BEFORE the else; you may ONLY place semi-colons AFTER the final curly-brace of the branch, and at the ends of lines of command BETWEEN the curly-braces. If I want to branch in more than two directions, I can use ELSE IF statements after my initial IF statement. Example: if (theSky == "blue") {
takeOffMyHat();
} else if (theSky == "gray") {
putOnMyOvercoat();
} else if (theSky == "black") {
putOnMyOvercoat();
getOutMyUmbrella();
};
Note: I may include a final ELSE statement at the end of my branch if I want a catch-all statement for everything that doesn't meet the previous conditions. With sequential if/else-if statements in a set, as soon as one of the conditions is met in the branch, that part of the code is executed and the branch is ended. You can't get TWO separate portions of the branch to execute if TWO of the conditions are true; to do that, you need to use TWO separate IF statements rather than an if/else-if branch like the one above. That's enough about branch logic for this introductory lecture. There are other forms of branch logic, very similar to the if statement, which we do not have the time to cover in this class. Logic: A Simplified Overview, Part TwoLoop LogicComputers are great at repeating things over and over again; it's one of the things that they do best. The computer's ability to repeat things precisely, again and again, has been classified in imperative programming languages as LOOP LOGIC. There are really only three kinds of loops, with many, many variations. Loop Type 1: Repeat an action WHILE, or for as long as, a condition is true. ExplanationsLoop Type 1: Repeat an action WHILE, or for as long as, a condition is true. For example, I could be testing to see whether a bowl of rice has rice in it. If the bowl of rice has rice in it, then I would eat a grain of rice. As long as the bowl still had rice in it, I would continue to eat a grain of rice each time the loop was executed. Once the bowl was found to be empty, the condition would become false and the loop would end. Example: while (theGrainsOfRiceInTheBowl > 0) {
eatAGrainOfRice();
};
Loop Type 2: Repeat an action for a particular length of time, or for a given number of repetitions. For example, I might wish to sort 3 shrimp into a basket. I could create a loop, called a FOR loop, which would allow me to perform my action three times, then stop. Each time through the loop, I would sort one shrimp into the basket. A local counter variable would be in place, which would be INCREMENTED (have 1 added to it) each time through the loop. When the counter reached 3, the loop would end. Example: for (myCounter = 0; myCounter < 3; myCounter++) {
sortShrimpIntoBasket();
};
In FOR loops, like the above example, the condition statement has three parts, which can be defined as (initialize; test; increment/decrement). Let's look at this portion of the FOR loop in greater detail. The first part, initialize, declares and initializes a local counter variable which may possess any name; in this example, the counter has been initialized to 0. Note: the local variable being declared here does NOT require the var keyword. The second part, test, evaluates whatever condition is placed there. In this example, I am testing the counter and seeing whether it is less than 3. If the counter is less than three, the condition is true and the statements between the curly-braces are executed. If the counter is greater than or equal to 3, than the condition is false and the loop ends without executing any further code. The third part, increment/decrement, is executed after the lines of code between the curly-braces have been executed. In this example, I am incrementing (or adding 1 to) my counter variable. Each time through the loop, then, the counter increases in number until it reaches 3; at that point, the condition check in the center becomes false and the loop ends, preventing further incrementation. In my live classes, I would act out the part of the computer running the loop. Obviously, that is not practical here. As an exercise, however, I am going to write out the iterations of the loop. myCounter is declared and initialized to 0. Is myCounter less than 3? Yes, so the loop executes, and sorts a shrimp into the basket. The third part of the structure is executed, incrementing the myCounter variable by 1. myCounter, then, is now equal to 1. Is myCounter less than 3? Yes, it is, so the loop executes, and sorts a shrimp into the basket. The myCounter variable is incremented again, and is now equal to 2. Is myCounter less than 3? Yes, it is, so the loop executes yet again, and sorts a shrimp into the basket. The myCounter variable is incremented again, and is now equal to 3. Is myCounter less than 3? No, myCounter is equal to 3, so the condition is false, and the loop ends. You would be amazed at the powerful things you can accomplish with this sort of mind-numbing repetition. The FOR loop is essential to code of any sophistication or ability. Loop Type 3: Repeat an action until something occurs to stop it. In my live classes, I act out the part of a computer-generated stopwatch, which keeps ticking away the seconds until someone presses a pretend button on my hand. You get the idea. This sort of "recursive" loop is usually created in JavaScript using the setTimeout() method of the Window object, which recursively calls its own function over and over again. A demonstration of code for this sort of loop is outside the scope of this class. One thing you may have noticed about loops is that, regardless of the type of loop under consideration, a loop performs ONE action or one SET of actions at a time; these actions are repeated We have barely scratched the surface of loop logic; there are a tremendous number of variations on the loop statements I've mentioned here. Loops are central to performing a wide variety of activities in JavaScript (as well as every other imperative programming language around). You might use loops to generate HTML code (creating repetitive structures like table rows, for instance), or for calculations of one sort or another, or to create game logic, or to access information from complex objects or arrays, or for any one of a vast number of other purposes. As I mentioned earlier, the use of logic, especially loop logic, is an entire world unto itself which is entirely beyond the scope of this introductory lecture. So, that's all the time we have for logic for now. For more information regarding JavaScript logic syntax, please see "JavaScript: The Definitive Guide", Chapter 6. The return KeywordA JavaScript function, when executed, may send some piece of data back to whatever process originally called it using the return keyword. For instance, I might make a calculation function which takes in numbers as arguments, performs a complex calculation (a mortgage payment calculation would be an appropriate example), and spits out an answer. The alert() method that you have used so far to spit out answers is obviously inadequate to real work; the return keyword is what you will need to use to get information out of a function. Built-in JavaScript methods use the return keyword to spit out many different types of values, which you will need to intercept and process for one reason or another, placing those returned values into local or global variables so that you can use and manipulate that information. In addition, you will be called upon to return values yourself, not only between functions, but also to the web browser. And it's not only numbers, strings, or booleans which can be returned from a function or method; references to objects can ALSO be returned from a function, such as a reference to a new browser window. I'll talk more about many of these subjects later on. Let's look at the addMe() function. Example: function addMe(myFirstNum, mySecondNum) {
var myAnswer = myFirstNum + mySecondNum;
alert(myAnswer);
}
The above example function DOES spit out an answer, but it does so via the medium of an alert dialog box. A function like this would NOT spit out information in an alert dialog box, it would normally be called by another function, which would need to receive the calculation result; this requires the use of the return keyword. Example (abbreviated): function addMe(myFirstNum, mySecondNum) {
var myAnswer = myFirstNum + mySecondNum;
return myAnswer;
}
Example (in context): function doStuff() {
var myNumberOfCats = 4;
var myNumberOfDogs = 2;
var myTotalNumberOfPets = addMe(myNumberOfCats, myNumberOfDogs);
alert(myTotalNumberOfPets);
}
function addMe(myFirstNum, mySecondNum) {
var myAnswer = myFirstNum + mySecondNum;
return myAnswer;
}
In the above example, I have called the addMe() function from inside doStuff(); this call passes myNumberOfCats and myNumberOfDogs as arguments to the addMe() function, which adds these values together (using its local variables, myFirstNum and mySecondNum). Once this calculation has been finished, the variable containing the result (myAnswer) is placed after the return keyword, which sends that information back to the calling function, doStuff(). In effect, the addMe() function call in doStuff() is replaced with whatever value is returned from the addMe() function; in this case, the number 6. That answer, 6, is put into the local variable, myTotalNumberOfPets, by the "gets" operator, whereupon that answer is displayed; for simplicity's sake, I have used the alert() method to display the answer, but a real function would probably be doing something much more involved with the information. This is an over-simplified demonstration of the return keyword. Obviously, you would never need to go through this much trouble just to add two numbers together. I am trying to show you the mechanics of this process using code that is extremely easy to analyze. Note: The return keyword MUST be part of the LAST statement in a function, because once the return keyword has sent its value back to the calling function, the function containing the return keyword ENDS, regardless of whether there is any more code following that keyword or not. Example: function addMe(myFirstNum, mySecondNum) {
var myAnswer = myFirstNum + mySecondNum;
return myAnswer;
alert(myAnswer);
}
In the above example, the call to the alert() method would NOT be executed because it follows the statement containing the return keyword. Again, after the return keyword statement has been executed, any lines of code following that statement are ignored. Many functions and methods in JavaScript return values of one sort or another to a calling process or function. In the remainder of this module, I will be showing you two different uses of return values which merely scratch the surface (once again) of the vast number of things you can do with this functionality. The window.open() Method RevisitedThe window.open() method RETURNS a reference to the new browser window ITSELF. If you store this REFERENCE to the new browser window in a variable, you can then manipulate the actual new browser window in many ways, via appropriate methods. Let's look at ONE of these methods, focus(). The focus() method of the Window object allows us to bring a browser window into FOCUS; that is to say, it allows us to SELECT the browser window without physically touching it, bringing that browser window in front of everything else. When you call the window.open() method, you must place the returned window reference into a variable, either global or local. Here's an example of what I mean. Example: function doStuff() {
var myWindow = window.open("http://www.yahoo.com/", "marian", "width=300,height=200");
}
Once you have the reference to the new window in a variable, you can access methods of that particular window via the variable name. For instance, after the window has been opened, we will FOCUS the window by calling the focus() method of the window instance of the Window object, using dot-syntax to do so. Example: function doStuff() {
var myWindow = window.open("http://www.yahoo.com/", "marian", "width=300,height=200");
myWindow.focus();
}
Using dot-syntax, I have called the focus() method of the variable, myWindow, which contains the reference to "marian", the new browser window; by doing so, I can bring "marian" forward. This can be important if the window "marian" has already been brought into existence, and has been deselected without closing it. If a window has been deselected without being closed, it gets blurred and sent behind the main browser window; when a method, like doStuff() above, opens "marian" again, the new URL and appearance information is applied to the existing "marian" window, but most web browsers will NOT focus "marian", bringing her forward, unless the focus() method has been applied to her. Of course, the most EXCITING thing about having a direct JavaScript reference to a browser window is that you can then send HTML, CSS, JavaScript, or other information into that new browser window, creating many dynamic possibilities (all of which, sadly, are beyond the scope of this class). Due to security restrictions in JavaScript, the CURRENT browser window can NOT be manipulated in the same way that a NEW browser window (created by the window.open() method) can. This restriction is in place to prevent JavaScript programmers from messing with a user's browser window without their permission, a very reasonable precaution. As I have mentioned, however, a NEW browser window, one which YOU have created, is not subject to these restrictions, and can be moved around, changed in dimension, brought forward and back, and many other things, all using built-in JavaScript methods accessed via a window reference in a variable, like the one in the example above. For more information on the Window object and its methods, see "JavaScript: The Definitive Guide", pp.704-749. Although I have not created an exercise for this section, I strongly urge you to experiment with some of these methods, to get comfortable with accessing your window via a variable containing the window's object reference. Remember that you may place that reference within either a local OR a global variable. I hope that I have whetted your appetite a little bit. Next, we're going to look at custom status bar messages; these also require the manipulation and passing of returned values, although in a considerably different manner. Custom Status Bar MessagesWhen you mouse over a hyper-reference, you usually see the URL of the HREF attribute listed in the status bar at the bottom of the browser window. Have you ever been to a web page where, as you moused over the hyper-references, you saw CUSTOM messages appear in the status bar instead of URLs? Here is an example page, demonstrating custom status bar messages. The first link on this demonstration page is a regular hyper-reference, which shows its URL in the status bar when you mouse over the link. The second and third links on the page, however, produce custom status bar messages at the bottom of the browser window when you mouse over those links. Spiffy, huh? There are three things you need to know in order to get this to work, which I will outline here. First, you will be addressing the status property of the window instance of the Window object, assigning it a string value using the "gets" operator; this will write your message to the status bar for the browser window. Example: window.status = "Hi There"; The second thing you need to know is that the WEB BROWSER itself needs to receive a boolean value of true when dealing with onMouseOver and onMouseOut event handlers in combination with the status property of the window object; if the web browser does NOT receive this boolean true value, the status bar does NOT change as it's supposed to. This true value is passed to the browser using the return keyword in the onMouseOver and onMouseOut event handlers. Example (abbreviated): onMouseOver="window.status='Hi'; return true;" The third thing you need to know is that the status property must be set back to an EMPTY STRING value on the onMouseOut event; otherwise, you MAY get your custom status message "stuck" in the status bar until the next onMouseOver event changes it. An empty string is represented by TWO quote marks right next to each other with NO SPACE (either double-quote marks or single-quote marks, depending on context): Example: <a href="#" onMouseOver="window.status='Hi'; return true;" The above example sets the status bar message to "Hi" on the onMouseOver event, and clears the status bar message on the onMouseOut event. Each event handler returns the value, true, back out to the browser by stating the return keyword, followed by the value, true, as the last statement in the event handler. Now, comes the confusing part. It is very rare for a web page to be dealing ONLY with a custom status message without some other action occuring at the same time, such as an image switch. Your onMouseOver and onMouseOut event handlers, then, will probably be calling a function which will be dealing with all of the commands that you need to have handled. The follow code would work: <html>
<head>
<title>Custom Status Bar Message Example</title>
<script type="text/javascript">
<!--
function showStatus(myMSG) {
window.status = myMSG;
// other commands here...
}
//-->
</script>
</head>
<body>
<p><a href="#" onMouseOver="showStatus('Hi'); return true;" onMouseOut="showStatus(''); return true;">Link Word</a></p>
</body>
</html>
In the above example, I am calling a function called showStatus() which changes the status bar, and then performs some other tasks. After showStatus() is executed, the second line of code in the onMouseOver or onMouseOut event handler is executed, which returns a value of true to the browser. This is not considered to be a sufficiently elegant solution, however, and is not always used. The following code is considered to be the MOST elegant solution, and is fairly common. Example: <html>
<head>
<title>Custom Status Bar Message Example</title>
<script type="text/javascript">
<!--
function showStatus(myMSG) {
window.status = myMSG;
// other commands here...
return true;
}
//-->
</script>
</head>
<body>
<p><a href="#" onMouseOver="return showStatus('Hi');" onMouseOut="return showStatus('');">Link Word</a></p>
</body>
</html>
In the above example, the onMouseOver and onMouseOut event handlers are going to return (to the browser) whatever value the function showStatus() returns. If you look at the showStatus() function, you can see that it returns a value of true (big surprise). Once showStatus() has finished executing, it returns the value of true to the event handler, essentially "replacing" the call to showStatus() with the value true; this value, then, is returned to the browser via the return keyword preceeding the call to showStatus(). You can see that elegant code sometimes requires the passing and re-passing of values, here and there and everywhere. Review this code sample a few times, possibly drawing out the sequence of where the values get passed and how they get there, until you feel comfortable with the events described above. Once you feel comfortable with this sequence, try coding the example yourself (typing out ALL of the code by hand, to give you the experience). Escape Characters in JavaScript StringsIn the example shown previously, you may have noticed the apostrophe (') character in the custom status messages. This apostrophe character is also the single-quote (') character which I was using to delineate the beginning and end of string values within event handlers; how did I get an EXTRA single-quote mark within a string delimited by single-quote marks? I used an ESCAPE CHARACTER, just as I would have done in regular HTML (except using different code). In JavaScript, escape characters/escape sequences are VERY simple. You simply put the backslash (\) character just before the character that you want to escape. Example (abbreviated):
Example (in context): onMouseOver="return showStatus('I am Michael\'s example');"
Any character can be escaped by using the backslash before the character within the string delimiters. Only certain specific characters actually need to be escaped, and, of course, you could NOT escape a double-quote mark in the example above because that would still confuse the HTML interpreter. See "JavaScript: The Definitive Guide", section 3.2.2 for more information on escape characters/escape sequences. Form Pulldown Menus Used as Navigation ElementsIn this section, I am going to talk about "submitting" a FORM to a JavaScript function, then extracting information from that form using dot syntax and a number of specialized keywords. To demonstrate this process, we are going to look at a FORM pulldown menu used as a navigational element. Here is an example of what I mean. In an earlier module, we discussed creating form pulldown menus, and using the VALUE attribute of the individual OPTION tags to store URL information. Example (abbreviated): <option value="http://www.yahoo.com/">Yahoo</option> For the purposes of this demonstration, I am going to name my SELECT tag "destinationList"; I do NOT need to name my FORM tag. Example: <form> <select name="destinationList"> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> <option value="http:/fog.ccsf.org/~srubin">Steve Rubin</option> </select> </form> When you "submit" your form to a JavaScript function, you will NOT use the submit INPUT; instead, you will use the generic button INPUT. You will pass the value, Note: the The following example presumes that the function I'm about to create is called Example (abbreviated): <input type="button" value="Go" onClick="goToNewPage(this.form);"> Example (in context): <form> <select name="destinationList"> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> <option value="http://fog.ccsf.org/~srubin">Steve Rubin</option> </select> <input type="button" value="Go" onClick="goToNewPage(this.form);"> </form> Now, I'm ready to create my function; the function will have one local argument variable, Example: function goToNewPage(myForm) {
// lines of code here...
}
In this function, I'm going to need to look at the destinationList SELECT tag within the form; this can be done using dot syntax. Example: myForm.destinationList Now, I'm going to need to look at the Example: myForm.destinationList.options[] What I really need to see, however, is the value property of the desired option in the Example: myForm.destinationList.options[].value The problem with this syntax is that we do not know WHICH option we want! In the Example: myForm.destinationList.options[2].value The above example will return the string value, Alright, this hard-coding is good enough, in its way, but HOW do I find out WHICH option the USER has selected? There is a special keyword of the SELECT tag, Example: myForm.destinationList.selectedIndex I need to put the above code INTO the array access operator ( Example: myForm.destinationList.options[myForm.destinationList.selectedIndex].value I would then place this extracted information into some sort of local variable. Example: var myDestination = myForm.destinationList.options[myForm.destinationList.selectedIndex].value; Once I have extracted the URL string value that I require, I will need to ASSIGN that value to the browser window's Example: window.location = "http://www.mozilla.org/"; Example: var myDestination = myForm.destinationList.options[myForm.destinationList.selectedIndex].value; window.location = myDestination; Example (complete function): function goToNewPage(myForm) {
var myDestination = myForm.destinationList.options[myForm.destinationList.selectedIndex].value;
window.location = myDestination;
}
In the example cited earlier, there was also a pulldown menu which changed the page location WITHOUT hitting a "Go" button. This functionality was achieved using the onChange event handler, which is triggered when the state of a form element is changed by the user; the onChange event handler would be added to the SELECT tag for the pulldown menu. Example: <select name="destinationList" onChange="goToNewPage(this.form);"> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> <option value="http://fog.ccsf.org/~srubin">Steve Rubin</option> </select> In the above example, the Yahoo option is pre-selected. If the user wishes to go to Yahoo, then, they will NOT be able to do so, because the onChange event handler is ONLY called when the state of the pulldown menu is CHANGED. To get around this problem, web programmers add some sort of blank option to the pulldown menu; this blank option usually tells the user what they ought to do with the pulldown menu. Example: <select name="destinationList" onChange="goToNewPage(this.form);"> <option>Choose Destination:</option> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> <option value="http://fog.ccsf.org/~srubin">Steve Rubin</option> </select> That's it! Here's the example page again. I strongly urge you to try typing out this code for yourself, by hand, to get a feel for the process. Some Final Thoughts about JavaScriptWe have only explored the simplest tasks in JavaScript; it is capable of doing so much more. With JavaScript, you can create Dynamic HTML pages, with animations, or contextual help menus, or special menu systems, or complete interactive applications built out of HTML elements. Flash and Director/Shockwave both use JavaScript as their native scripting language, opening the doorway to interactive animated games, and interfaces, and multimedia-rich experiences of every description. On the Web, JavaScript is the glue that ties all of the multimedia elements together, and allows you to make really interesting things out of basic pieces. I hope that you have found our JavaScript discussion interesting, and that it has whetted your appetite for more programming, or, at the very least, given you a little necessary information. Remember that programming itself is all about breaking big things down into the smallest, most manageable single tasks; always start with the non-controversial things, single tasks that you understand, and get those down FIRST. Once you've gotten the easy things down, you'll be surprised at how much more readily everything else falls into place! "Divide and Conquer" is the rule of law in programming; if you divide your problem into simple bits, you'll conquer the entire task! If you really want to learn JavaScript so that you can harness its interactive power, I strongly urge you to start coding projects of every description NOW. Flash, with its streaming sound and animation capabilities, is, by far, the most accessible environment for creating immediate, fun, "flashy" pieces using JavaScript programming that will provide you with a lot of immediate gratification. Dynamic HTML work, however, with its direct connectedness to HTML, is more at the heart of JavaScript's DOM and other built-in features. Whichever way you turn, JavaScript programming will give you a lot of satisfaction.
|