home > javascript > functions

javascript functions

you can make your own commands in javascript. they are called "functions". as in all programming languages, there are some rules you have to learn.

what goes where:

the previous page (about events and actions) shows how you can call a piece of javascript code from within the html:

<a href="somepage.htm" onmouseover="window.status='Roll over me'; return true">

but it is much more elegant (and more readable) when you make your own "showText" function.

<a href="somepage.htm" onmouseover="showText()">

this "showText()" function will then contain the "window.status='Roll over me'; return true" code. you always have to place the () after the name of the function:
showText()

where do you place your own function in the webpage?
a good spot is in the <head> of the html.

<html>
<head>
<script language="javascript">
...the first function...
...the second function...
...the third function...
</script>

<title>the grocery store</title>
<head>

<body>
.......
   
declare:

...the first function...

look at the code on how you declare (=create) your own function

function showText() {
   // show text on the status bar
   window.status='Roll over me';
   return true;
}

let's look at the code line by line.

function showText() {      the keyword "function" tells javascript that you are going to make your own function. you name your function "showText()". don't forget the () immediately after the name, no spaces. try to give it a useful name. "myFunction()" or "doit()" is a very bad name.
all the javascript commands that belong to your function go between the { and }
this way javascript knows where the function starts and where it ends.
  // show text on the status bar   on the next line, you make a comment in plain text about what your function does. in the future you will be glad you did. lines that start with // will be ignored by javascript. when you want to type some more text on the next line, also start that line with //
  window.status='Roll over me';   your first javascript command that belongs to the function and actually does something. you have to get used to it, that every command ends with a ;
lines beginning with "function" and "//" do not have to end with a ;
  return true;   your second command.
}   the end of the list of commands that belong to the function. when you call the function, every line wil be executed, top-down.

to make your code more readable, you indent all the lines that belong to the function. that means: every line after the { and stop indenting at the last }
the best way to do it, is to use the tab on your keyboard. dreamweaver is so clever as to automatically tab every next line. this is a programming habit.

use one line for every command.