Tutorial: The Art of Passing Parameters in Javascript
Posted:Are you still confused about the whys and hows of passing parameters in javascript code? Then read this easy tutorial to learn the ropes.
One of the most confusing concepts to grasp in javascript is that of
passing
parameters. But it's really very easy to understand. The best way to
help you get the logic behind it all is through the use of a real life
example.
A Background Color Button Changer
Let's say that you wanted to create a button on your page that will change the color of your background once clicked through the use of a function. For our example, let me post the code for both the button and the function:Code for button:
<input type="button" value="click me!" onClick="changeColor()">The function:
//our button
<script language="javascript">Now this works well enough. When you click on the button, the event handler attached to it, onClick="change Color ()", activates the function called "changeColor", which changes the background color of your web page to red.
function changeColor() {
document.bgColor='red'
}
</script>
But going this route is very limited. What would happen if we wanted
more
than one button? For example, one button that changes the background
red,
a second one that changes the background green,
and a third one that changes the background yellow?
A Three Buttoned Background Color Changer
If we tried to rewrite our javascript to accomodate our new additions, we would be faced with the possibility of having to rewrite a new function for each button. For example, in the script below, I have created three new functions, each that will change the background a different color:Code for buttons:
<input type="button" value="red" onClick="function makeRed()">
// button that changes background red<input type="button" value="green" onClick="function makeGreen()">
// button that changes background green<input type="button" value="click me!" onClick="makeYellow()">
// button that changes background yellow
And here is what the script would look like, functions and all:
<script language="javascript">Can you guess the problem of going this route? That's right! Now your javascript coding is becoming a bit cumbersome and bloated. Imagine if you had something like 20 buttons to change the background color with? You would have to write 20 different functions. Definitely. Not. Cool!
function makeRed() {
document.bgColor="red"
}function makeGreen() {
document.bgColor="green"
}function makeYellow() {
document.bgColor="red"
}
</script>
So now, ladies in gentlemen, enter the beauty and the art of passing
parameters, and how it will make life easier for yourself.