Writing and executing javascript functions
This is a short tutorial that will show you how to write javascript functions and then how to execute them.
Let's start by looking at a basic function.
This function will take 2 numbers and find the percentage of the first number in the second. ie. if the first no. was 1 and the second 10 the output would be 10%
Let's break this down
All javascript functions start with the word function and are preceded by the function name, carefull not to use any of the inbuilt functions as your name.
Following the function name and contained in parenthesis (normal brackets not curly or square ones) are the functions arguments. The arguments are a way of passing values to the function, for example if we wanted to get the percentage of 2 in 5 elsewhere in our script we would simply write getPercent(2,5).
The rest of the code is the operaions to performed when the function is fired. This is always contained by curly brackets.
So that's how we write a function but how do we trigger it at the time or on the event that we want? Well there are a couple of ways but to start with we will look at using inline event handlers. To do this we can add an event handler to an html element. Some popular and usefull event handlers are:
onClick(); triggers the function when the element is clicked on
onMouseover(); triggers the function when the mouse is over the element
onLoad(); usually added to the body tag to initialise any functions we want to trigger when the page loads
Below are some example implementations:
We can also apply event handles to html elements directly from our javascript code. Below are some examples:
