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 is passed into our variable "what". In this case we print the "what" variable in an alert box. We could have printed it to the browser page if we were so inclined and we hadn't just sent our user to Google.
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.
Passing Argument - See in Action (new window)
Click HERE to comment or discuss at iLoveTheCode GOOGLE Group