Welcome to S-Design
The home of your bespoke, professional, fast-loading, interactive, database-driven web presence.
Menu
JAVASCRIPT TUTORIALS


JAVASCRIPT Functions

Functions allow to to write a piece of code once, and then reuse it over and over again. This is not the same as JavScript Loops which allow to to use the same peice of code a set number of times.

Lets take a look at the for loop we used in the previous JavaScript Loops chapter: <html>
<head>
<script>
var vegtext='';
veg=["peas","carrots","parsnips","potatoes","broccoli"];
for(i=0;i<veg.length;i++){
vegtext+=veg[i];
}
document.getElementById('veg').innerHTML=vegtext;
</script>
</head>
<body>
<div id="veg">
</div>
</body>
</html>

Now what if we wanted to print out not only the vegetable name, but include an image/photograph of that vegetable too. We could simply include the code for this inside the for loop, but that means we'd have to write it out each time we wanted to do the same thing in other scripts.
Instead, we can write a function once, to generate the image code of the vegetable images, and simply use it whenever we want.
Here's a simple function to generate and image tag from the vegetable name: <script>
function VegPic(vegname){
return '<img src="images/'+vegname+'.jpg">';
}
</script>
This simple function returns an image tag based upon what we send it in the vegname variable. So if we called this function with VegPic('carrots');, it would return <img src="images/carrots.jpg">

Here's how to use the for loop and the function together: <script>
var vegtext='';
function VegPic(vegname){
return '<img src="images/'+vegname+'.jpg">';
}
veg=["peas","carrots","parsnips","potatoes","broccoli"];
for(i=0;i<veg.length);i++){
vegtext+=veg[i];
vegtext+=VegPic(veg[i]);
}
document.getElementById('veg').innerHTML=vegtext;
</script>
This would print out the name of the vegetable, followed by an image of the vegetable. (this assumes that you had previously created all of the vegetable images and stored them inside a directory called images!)

What if you need to go through the vegetable array and get the vegetable image, in a loop, many times over in your script?
You could combine the loop and image fetching inside one function, like this: <script>
var vegtext='';
function VegPic(veg){
for(i=0;i<veg.length;i++){
vegtext+=veg[i];
vegtext+='<img src="images/'+veg[i]+'.jpg">';
}
}
veg=["peas","carrots","parsnips","potatoes","broccoli"];
VegPic(veg);
document.getElementById('veg').innerHTML=vegtext;
</script>
Here we simply pass the whole veg array to the VegPic function and let it perform the loop and image creation.

Title