A Wired.com user account lets you create, edit and comment on Webmonkey articles. You will also be able to contribute to the Wired How-To Wiki and comment on news stories at Wired.com.
It's fast and free.
processing...Retrieve Sign In
Please enter your e-mail address or username below. Your username and password will be sent to the e-mail address you provided us.
processing...Welcome to Webmonkey
- edit articles
- add to the code library
- design and write a tutorial
- comment on any Webmonkey article
Sign In Information Sent
Steal JavaScript
/skill level/
/viewed/
As Stewart Brand famously said, "Information wants to be free." And while generic human greed generally stands in the way of gratis info, JavaScript is a happy exception. The JavaScript code you covet on other people's pages is, in most cases, yours for the taking.
The trouble is, you can't just grab someone else's code, drop it into your Web page, and have it work. You actually have to learn javascript, even just the basics. Otherwise you may have trouble making that neat rollover or form checker function the way it should on your own page.
That's where this article comes in. I'll give you just enough JavaScript know-how (and not one bit more) to effectively steal code and still adhere to the first great virtue of the programmer:laziness. By the time you finish with this lesson, you should be able to take someone else's code and use it for your own unique purposes.
But lest I get spammed with hate mail, let me make it perfectly clear that "stealing" code is only OK if it's not really stealing. There's lots of JavaScript out there that was meant to be shared, and most people will be happy for you to use their code as long as you give them credit and you use it with your own content (i.e., grabbing code to make your own buttons into rollovers is good; stealing someone else's code and buttons and layout is bad). Finally, if you're not sure it's kosher to use a particular bit of JavaScript, then you need to ask the original author first.
Aside from making sure your code is moral, you also need to know how to cut and paste text and view source code. You got all that? OK then, let's dig in, starting with script tags.
Contents |
Script Tags
To teach you how to tweak JavaScript code so it works on your own Web page, let's take a look at a page that's using JavaScript to set the background color randomly each time a user hits Reload:
<html>
<head>
<script language="JavaScript">
<!-- hide from old browsers
function setBackgroundColor(color1, color2, color3, color4) {
theColors = new Array(color1, color2, color3, color4);
var whichColor = Math.round(Math.random()*1000) % 4;
document.bgColor = theColors[whichColor];
}
// stop hiding -->
</script>
</head>
<body onLoad="setBackgroundColor('#ff0000','#00ff00','#ffff00','#3333ff');">
<font face="Arial, Helvetica, sans-serif" size="4">
Hit Reload (or Refresh if you're using Internet Explorer)
to see a new background.
</font>
</body>
</html>
To see what this code will do, check out the actual page and hit Reload a few times. See all the pretty colors? Let's learn how it works.
There are several important things going on here. First of all, notice the <script> tags. These tags are used to separate JavaScript from the regular HTML code in your document. Everything in between <script> and </script> is interpreted as JavaScript. Old browsers from before the days of JavaScript should simply ignore everything inside the <script> tags, but in some cases, they try to display the code as text. For this reason, it's good form to comment out your JavaScript with an initial line that begins "<!--" and a final line that begins with "//" and ends with "-->".
These <script> blocks can appear anywhere in your document, but be aware that the JavaScript instructions within the <script> tags will be executed as they appear. For example, a command located in the <head> of a document will generally be executed before one located in the <body>.
Now that you know where you can put that JavaScript (anywhere), let's take a look at what's going on inside the script.
Functions (and Their Arguments)
Remember this part of the code from the example on the previous page?
function setBackgroundColor(color1, color2, color3, color4) {
theColors = new Array(color1, color2, color3, color4);
var whichColor = Math.round(Math.random()*1000) % 4;
document.bgColor = theColors[whichColor];
}
This is called a function, which is basically a set of related commands grouped together so they can all be executed at once. It's easy to spot a function because it (surprise!) always begins with the word function and is followed by the name of the function (in this case "setBackgroundColor"). The parentheses after the name contain the function's arguments. The body of the function is enclosed in braces ({ }).
Arguments, Variables, and Type
Sometimes a function needs to be told what to do. In the setBackgroundColor() example, you need to tell the function which colors to use. You do this by specifying arguments to the function within the parentheses, like so:setBackgroundColor('red','green','blue','black'); (In this example, there are four arguments:red, green, blue, and black.)
Another way to separate specific information (such as the colors to be used) from the main function is to use variables or arrays. For example, we could have written our example using variables, like this:
var color1 = '#FF0000';
var color2 = 'red';
var color3 = 'green';
var color4 = 'blue';
function setBackgroundColor() {
theColors = new Array(color1, color2, color3, color4);
var whichColor = Math.round(Math.random()*1000) % 4;
document.bgColor = theColors[whichColor];
}
Variables are just a way to store information. The statement var color1 = '#FF0000'; says that the variable color1 should be set to '#FF0000'. And an array is just a list of variables:
theColors = new Array('#FF0000','red','green','blue');
function setBackgroundColor() {
var whichColor = Math.round(Math.random()*1000) % 4;
document.bgColor = theColors[whichColor];
}
The reason you need to know all this is that you may have to modify the values of variables and arrays to make someone else's script work for you. For example, if that person has a variable set to her site's domain (var siteRoot = 'http://www.webmonkey.com/';), you would need to change that to your own domain to make the script work on your site.
The last thing you need to know about variables is type, which refers to the several different types of information that can be stored in a variable:strings, numbers, and objects. You don't need to delve too deeply into these different types, but you should know how to recognize them. Let's take a quick look at each of them.
Basically, strings are text, such as, "I am stealing JavaScript" or "Nadav is not a giant ant." Numbers are, well, numbers:2 or 3,123. Strings are always written inside quotation marks, numbers are not. For example, 2 is a number but '2' is a string (similarly 2+2 is the number 4 while '2' + '2' is the string '22').
If you're really sharp you may have noticed that I sometimes use double quotes (") and sometimes use single quotes ('). JavaScript doesn't care which you use as long as you don't nest one kind within the same kind:
<body onload="alert("this is bad")">
<body onload="alert('this is good')">
(If you can't tell the difference, look really closely at the quotation marks.)
The third type of variable, an object, is a bit more complex. Since you'll rarely need to modify them, we'll keep this section brief. Objects refer to parts of the page:The document is an object, each image is an object, a text field in an HTML form is an object. If you see something that looks like a string (such as a word in a function's list of arguments) but you notice it isn't enclosed in quotation marks, it's probably an object:
<body onload="alert(document.URL)">
The most likely reason you'll be dealing with objects is if the script you're stealing refers to objects on the page by name. Let's take a look at a little example. Type something into this text box and then submit the form:
Here's what the code that generated this form looks like:
<form name="myForm" onSubmit="alert('You entered:'
+ document.myForm.myTextField.value); return false;">
<input type="text" name="myTextField">
<input type="submit" name="Submit" value="Submit">
</form>
One of the most common problems you'll run into when you try to use someone else's code is that the script is expecting objects (such as form fields) to be named a certain way. To make the script work you either need to modify the script to match your own object names or name your objects to match the script.
One last thing is pretty important:Variables are objects too. For example, you could set a variable to store an object such as the page's URL:
var myLocation = document.URL;
Whew! I bet all that's a bit more technical than you thought we'd be getting. If it seems like a lot to digest, that's OK - just as long as you understand that if you need to change the information in someone else's script you also need to keep the variable types the same (if that person used a string you'll want to use a string too).
Calling Functions
How do you use functions, anyway? Well, there are two main ways to invoke (or call) a function. The most straightforward is to put the name of the function in between <script> tags like any other JavaScript command. For example:
<script>
<!-- remember to comment your script
setBackgroundColor('#ff0000','#00ff00','#ffff00','#3333ff');
// close the comment -->
</script>
Note how the arguments (the four colors) are specified inside the parentheses.
The second way functions get called is a bit more interesting. It's called event handlers, which requires a bit more explaining.
Events and Event Handlers
In JavaScript, an event occurs whenever something happens on a Web page. Events occur when the page finishes loading or when users click on a link or move their cursors over images. The cool thing about events is that you can specify what JavaScript should run when a given event happens. For example, you could have an image change whenever the cursor moves over it or you could select a random background color to appear each time a page loads (as in our example).
The most common way to specify what happens when an event occurs is to embed an event handler in an HTML tag, as we did in our random background color example:
<body onLoad="setBackgroundColor('#ff0000','#00ff00','#ffff00','#3333ff');">
In this example, onLoad is an event handler because it tells the JavaScript interpreter how to handle the load event, which occurs whenever the body loads (because it's in the HTML body tag).
When the body loads, this line of code will call the setBackgroundColor function, which will then randomly pick a new color for the background. JavaScript authors frequently use the onLoad handler in the body tag to run a function whenever the page loads because this is a particularly handy time to get things done (since the user is already waiting patiently).
There are a lot of different event handlers, but here are the ones you'll run into most often:
<body onLoad="someFunction();">
<a href="#" onMouseOver="someFunction();"
onMouseOut="anotherFunction();"
onClick="yaFunction();">
<a href="javascript:someFunction();">
<form onSubmit="someFunction();">
<input type="button" onClick="someFunction();">
<select onChange="someFunction();">
That's about it. You now have everything you need to know to make a burgled JavaScript work on your own pages. Now let's put it all together.
Making It All Work
OK, now you know what JavaScript looks like and how to use functions and event handlers. You're ready to start swipin' some code. Just go out, find a page that uses JavaScript to do something you want to do, and view source. Then find the JavaScript functions and statements that do what you want and copy them to your own page. Finally, look for arguments and variables you need to modify in your own HTML.
If you've done something wrong, either nothing will happen or you'll get an error message like this:
(If you're using a recent version of Netscape or Internet Explorer, error messages may be suppressed.)
Debugging JavaScript can be a somewhat time-consuming process but you now know enough to start hacking away at it. Be patient and you should be able to make most any script work on your page.
Now go forth like Oliver Twist under the benevolent stewardship of Fagin and steal, steal, steal!
Or, if this tip of the JavaScript iceberg has piqued your curiosity, I heartily recommend Thau!'s extensive (and fun) JavaScript Tutorial, which will teach you how to write the kind of scripts other people will want to steal.
- This page was last modified 06:32, 15 May 2008.
/related_articles/
Special Offer For Webmonkey Users
WIRED magazine:
The first word on how technology is changing our world.