RSS Feed

This is part 2 of the “jQuery From Scratch” series of tutorials. If you have not read part 1, you can have a quick read. This tutorial will deal with writing and executing functions in JavaScript.

jQuery does not provide a quick method for creating functions. That’s because it doesn’t need to. So what are functions? Instead of giving you the standard definition, I’ll explain why/when you might want to create and use functions in your code.

Say that you have a block of code that you would like executed on multiple events. This code could do anything. The principal to consider is that you will need this code to be executed as multiple events are triggered. Instead of writing the code over and over again for each event, you could add this code to a function and then execute this function whenever you want the code to be executed.

Creating Functions

To create a function called “aFunction”, we could write:

function aFunction() {

Say that we wanted to alert the user each time this function is executed. We could write:

function aFunction() {
  alert("Hello World!");

In this example, the user is alerted each time the function is executed.

Executing Functions

We can execute the function when any event is triggered. If we wanted the function to be executed when the page has loaded, we could write:

$(document).ready(function() {

This is pretty straightforwards… but there’s more to functions.

Passing Arguments

We can pass values into the function that are used when the code is executed.  To demonstrate this, I’ll continue with the example that I’ve been using.  Instead of displaying “Hello World!” whenever the function is executed, we could pass the message into the function:

function aFunction(msg) {

We could now execute the function as follows (to display any old message to the visitor) when the page has loaded:

$(document).ready(function() {
  aFunction('Just a short message');

We could pass multiple arguments by separating them with a comma:

function addNumbers(num1,num2) {
  var total = num1 + num2;
  return total;

The function above will simply return the total value of the two numbers passed as arguments. It is important to note that the value returned will not by output to the page. You could print the returned value to the page by using document.write:

$(document).ready(function() {

<a href="">some site</a>
<em>some emphasized text</em>
<strong>some bold text</strong>
<pre lang="">some code</pre>
To add code to your comments, simply wrap the code inside <pre> tags. Syntax highlighting will be added if you define the language. Example:
<pre lang="php">some code</pre>

Supported "lang" attribute values: html4strict, css, php, javascript, xml & mysql