Passing an Argument or Variable to a Javascript
This sounds harder than it is. We are going to pass an argument to a function.
We will name our function sayGoodbye() because we want it to sound kind of sad.
Here is our new function for the top of our HTML document.
function sayGoodbye(what) {
alert(what);
}
The word "what" can be any word as long as it is the same in both places. (The alert() method is built-in to Javascript and it opens an alert box in your browser.)
Create a link that calls our new function. (Use single quotes because we are already inside double quotes.)
<a href="http://google.com" onClick="sayGoodbye('Tell Google I said Hi');return true">Google</a>
When we click this link, whatever text is in the single quotes (our argument) is passed into our variable "what". In this case we display the "what" variable in an alert box. We could have used that value in our function numerous ways, such as identifying the link that was clicked. Example:
function sayGoodbye(what) {
if (what == 1) {
alert('Link Uno');
}
else {
alert('Link Dos');
}
}
<a href="#" onClick="sayGoodbye(1);return false">Link One</a> | <a href="#" onClick="sayGoodbye(2);return false">Link Two</a>
NOTE: You may have noticed that there are no quotation marks around the 1, 2, or the 1 in == 1. That is because we passed a number rather than a string. A string would have required quotation marks like the first example above.
Copy and Paste Javascript (two sections):
Top of HTML:
<script type=text/javascript>
<!--
function sayGoodbye(what) {
alert(what);
}
-->
</script>
Link:
<a href="http://google.com" onClick="sayGoodbye('Tell Google I said Hi');return true">Google</a>
In the link, the "return true" means go to the link that is being clicked on. "return false" would stop from going to the link.