Writing Your Own JavaScript Functions
This article is excerpted from Chapter 6 of The Book of JavaScript with permission from No Starch Press
In this chapter we’re going to focus on a programming concept–writing your own functions. Knowing how to write your own functions will improve almost any JavaScript you create. In fact, you’ll see how custom-made functions can enhance several of the JavaScript tricks you’ve already learned. In this chapter, you’ll learn how to:
- Write your own functions
- Use homemade functions to improve your code
- Write functions you can cut and paste into whatever pages you want
We’ll be using homemade functions in every chapter from now on, so pay extra-close attention to what’s going on in this chapter. you’ll be glad you did.
Functions as Shortcuts
Functions aren’t anything new. you’ve already seen a number of functions that come built in to JavaScript. The alert() function, for example, takes whatever text you put inside the parentheses and displays an alert box with that text.
In its simplest form, function is just a shorthand name for a series of JavaScript instructions. When you call the alert() function, JavaScript under stands it as a command to carry out some task, such as opening a window that has an OK button and a close button and putting some text in the window.
The functions you create act as shorthand as well. Let’s say you want to write a link that opens a small window and then centers that window on the screen if the visitor is using Netscape 4.0 or above. You could write a link resembling Figure 6-1 (most of the code in it is similar to Figure 5-10).
<a href = “#” onClick = “if ((parseInt(navigator.appVersion) > 3)
&& (navigator.appName == ‘Netscape’)) {
var the_window = window.open(‘http://www.nostarch.com/’,
‘the_window’,’height=200,width=200′);
var screen_height = window.screen.availHeight;
var screen_width = window.screen.availWidth;
var left_point = parseInt(screen_width / 2) – 100;
var top_point = parseInt(screen_height / 2) – 100;
the_window.moveTo(left_point, top_point);
} return false;”>Click me to open a small centered window</a>
Figure 6-1: A link that opens a small window and centers it in Netscape 4 and above– this won’t work in Internet Explorer (see note at the end of Chapter 5)
However, it is not a good idea to write a link in this way: There’stoo much JavaScript embedded in the HTML. This makes HTML hard to follow, even for people who know JavaScript. Furthermore, if you want two or three links on your page, your HTML becomes even uglier and your page’s download time increases. Even more problematic, if you want to change the code to affect window size or centering, you have to make the change everywhere you put the link.
The solution to these problems is to give all the JavaScript in Figure 6-1 a name and then simply call that name when you want to open and center a window. That’s exactly what homemade functions are for: They allow you to call a set of JavaScript instructions (the function) just by using its name.
Basic Structure of JavaScript Functions
Figure 6-2 shows you the skeleton of a homemade function.
function functionName()
{ a line of JavaScript; another line of JavaScript; more lines of JavaScript;
}
Figure 6-2: The basic structure of a homemade function
A function definition starts with the word function. When JavaScript sees that word, it knows you’re about to define the subsequent bunch of JavaScript as a function.
Naming Your Functions
Next comes the function’sname. The rules for naming a function are similar to those for naming a variable. The first character must be a letter; the rest of the characters can include letters, numbers, dashes, and underscores. No other characters, including spaces, are allowed. Like variables, function names are case sensitive, so JavaScript will consider a function called feedTheCat() to be different from a function called FeedTheCat().
Make sure you don’t give a function and a variable the same name. If you have a variable called my_cat and a function called my_cat, JavaScript will forget either what the function’ssupposed to do or what value you’ve stored in the my_cat variable. Because of this weird behavior, and because function names are case sensitive, it makes sense to have a different convention for naming functions than for naming variables. For variables I use lowercase letters with underscores, and for functions I use what’s called in-caps or camel-caps notation. Names in this notation style consist of strings of words without spaces, in which every word except the first is initial-capitalized, as in openAndCenterTheWindow(), myCat(), and printDate(). In-caps notation is a pretty common convention and should serve you well.
Parentheses and Curly Brackets
A pair of parentheses follows the function’sname. For now, you won’t be entering anything between them, but they’re still necessary.
After the parentheses you need a pair of curly brackets. Between these brackets you’ll write the JavaScript that will run when the function is called.
An Example of a Simple Function
Figure 6-3 shows you how the window-centering code in Figure 5-10 looks rewritten as a web page containing a function. Notice that the link calling the function (X) has the same form as a link that calls a built-in JavaScript function–the function name appears inside an onClick.
Writing Your Own JavaScript Functions 85
<html>
<head>
<title>Getting Centered</title>
<script type = “text/javascript”>
<!– hide me from older browsers
function openAndCenterWindow(){
if ((parseInt(navigator.appVersion) > 3) && (navigator.appName == “Netscape”)) {
var the_window =window.open(‘http://www.nostarch.com/’,’the_window’,’height=200,width=200′);
var screen_height = window.screen.availHeight;
var screen_width = window.screen.availWidth;
var left_point = parseInt(screen_width / 2) – 100;
var top_point = parseInt(screen_height / 2) – 100;
the_window.moveTo(left_point, top_point);
}}// show me –>
</script>
</head>
<body>
X <a href = “#” onClick = “openAndCenterWindow(); return false;”>Click me to open a small centered window</a>
</body>
</html>
Figure 6-3: Opening and centering a window using a function