jQuery Events

We can now utilize our JavaScript functions by referencing them as events in jQuery. A few of these events will save your life. Remember back when you used the HTML element attributes like onclick? Now, you can simply use the jQuery selectors that are listening the entire time the user is viewing the page. Listeners are useful so you are crowding your code with onclicks and other HTML action attributes. So, whenever you want to change an event, you can just go to your JavaScript code and not have to sift through your HTML.

Example
<button>Click Me!</button>
<ol>
    <li>
        Item 1
    </li>
    <li>
        Item 2
    </li>
</ol>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$("button").click(function()
{
    $('ol li:first').hide();
});
</script>

As you can see, I select the ol, and then I select its first child li:first node. I Invoke the event hide, which basically sets the node’s style to invisible.

Events in jQuery are not limited to a single element. You can actually get fairly complicated passing in classes and names to have track events of any of the elements in that group. This is great practice as it is very dynamic and requires much less code than a ton of static JavaScript functions.

Common Events

  • $(document).ready(function) – starts when the selector has been loaded (document is the common selector)
  • $(selector).focus(function) – starts when the selector gains focus
  • $(selector).mouseover(function) – starts when the user hovers over the element
  • $("input").keypress(function) – starts when a key is pressed
  • $("input").keydown(function) – starts when a key is pressed down
  • $("input").keyup(function) – starts when a key is released
  • $(window).scroll(function) – starts when the user scrolls the selector (window is the common selector)

These are just a few of the important events, but please feel free to go jQuery’s tutorial on events to see the rest of the events I cannot overstate the importance of the events in jQuery. Use them to control when and how you want to start jQuery functions.

jQuery With AJAX

Your life just got much easier my friend. A quality AJAX script that does a simple GET or POST is massive. With jQuery, you can make that much more manageable. I should go ahead and tell you upfront that AJAX is a technology that allows you to send requests to a server without ever reloading the page. Another important note is jQuery’s ajax method is not the only ajax that is possible with jQuery.

The two most important (I believe):

  • .load(url,data,callback) – loads data from selected object
  • .ajax(settings) – loads data into an XMLHttpRequest object
Example <div id="firstLoadDiv">I am special</div>
<div id="secondLoadDiv">I am not</div>
<input id=’buttonLoadId’ name="buttonLoad" type="button" value="Do AJAX!"/>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$("#buttonLoadId").click(function()
{
$(‘#secondLoadDiv’).load(window.location +’ #firstLoadDiv’);//notice the div id reference
});
</script>

We are actually talking to ourselves on this one. We use the load() method to talk to the jquery-ajax.php file. We go on to inquire in even more detail. We use the div id #firstLoadDiv right after our file reference to get what the contents of that div. Now, we move onto the awesome ajax() method.

Example //PHP File
<?php
echo "We win!";
?>
//end PHP File
//HTML File
<div id="firstAjaxDiv">Default Text</div>
<input id=’buttonOneId’ name="buttonOne" type="button" value="Do AJAX!"/>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$("#buttonOneId").click(function()
{
url = (‘ajaxTest.php’);
$.ajax(
{
url: url,
success: function(data)
{
if(data !="")
{
$(‘#firstAjaxDiv’).html(data);
}
},
error: function()
{
$(‘#firstAjaxDiv’).html(‘It failed…’);
}
});
});
</script>
//end HTML File

It is somewhat similar to the load() method, but it has a much better layout. We set the url to another page called ajaxTest.php. Then we have two properties that have functions in them. The success property or setting has a function that sets our div firstAjaxDiv‘s html to the data we receive from our request to the url. Granted, .html is not the best method, but it does get the job done. Second, we have another property error that has a function that tells us if our request went through successfully.

That is some pretty advanced stuff you just did. Take a break you earned it.

As always, this is just to better your understanding. You can check out jQuery’s AJAX Functions for a full list of the JQuery AJAX methods.

Break and Continue

While we are talking about loops, JavaScript has two powerful statements that also be used, break and continue. You will gain an understanding of each one does in the following examples.

Example
var i = 0;
for (i = 0;i <= 5;i++)
{
    if (i==2)
    {
        break;
    }
    document.write(i);
    document.write("<br />");
}
document.write( "End of for loop" );
Result
0
1
End of for loop

Once the var i reaches 2 in the for loop, it meets the conditional statement i == 2, which is then executed. The statement executed is break;. Once break is executed it actually breaks us out of the for loop, which is why when i equals 2, we exit the for loop and execute document.write( “End of for loop”); instead of ending the for loop when i equals 5.

Example
var i = 0;
for (i = 0;i <= 5;i++)
{
    if (i==2)
    {
    continue;
    }
    document.write(i);
    document.write("<br />");
}
document.write( "End of for loop" );
Result
0
1
3
4
5
End of for loop

It seems pretty obvious that continue different than the break. Notice how the only result not printed is 2. The continue; basically says let’s skip out of this particular instance of the loop and move onto the next one. So when we are running through the instance where i becomes equal to 2, we meet the conditional statement if( i == 2) where it is true. Then, we execute the continue, which stops us from executing the following statements in the loop. We then run through the next instance of the loop where i equals 3. Since we don’t meet the conditional statement this time, we will write the following statements and will never enter into conditional if(i == 2).

Optional Arguments

Now that we have a better understanding of JavaScript Functions, we can now provide optional arguments to those functions. Why would you want an optional argument in a function you might ask? Well, there are many different reasons, but a good example is in the actual structure of JavaScript. For example, the string method of split has a required argument and an optional one. The required argument is the separator, which is what character(s) you will use to divide the string. The optional argument is limit where you specify how many times you want to split the string. So, if I only wanted to split the string to the first instance of the separator, I would just provide a 1. Example please!

How Optional Arguments Work

Example
message = "The quick brown fox jumped over the lazy dog.";
console.log(message.split(""));
Result [“T”, “h”, “e”, ” “, “q”, “u”, “i”, “c”, “k”, ” “, “b”, “r”, “o”, “w”, “n”, ” “, “f”, “o”, “x”, ” “, “j”, “u”, “m”, “p”, “e”, “d”, ” “, “o”, “v”, “e”, “r”, ” “, “t”, “h”, “e”, ” “, “l”, “a”, “z”, “y”, ” “, “d”, “o”, “g”, “.”]

Now, we put in the optional argument of 1.

Example
message = "The quick brown fox jumped over the lazy dog.";
console.log(message.split("",1));
Result [“T”]

That is cool and all, but how exactly do we create functions that can do this? If we create a function with 2 arguments and only provide 1, the second argument will return undefined. First, JavaScript doesn’t yell at you if you have multiple arguments, but don’t specify them when you call the function. JavaScript only screams bloody murder when you leave off an argument that sets a variable inside the function that is called. For example…

Example
function printMessage(times, message)
{
	for(var a = 0; a < times; a++)
	{
		console.log(times);
	}
}
printMessage(4);
Result 4
4
4
4

See JavaScript doesn’t care that you left off the message argument because it didn’t need it anywhere in the function. Now, if you were to use message in the function, it would return undefined.

Creating Optional Arguments

Let’s get back to actually creating optional arguments in our functions. You will notice that the easiest and best way to create optional arguments is to put them at the end of the argument list. Sometimes you might want two optional arguments where only one has to be required. However, that is much more complicated and outside the scope of this simple tutorial.

Example
function printMessage(times, message)
{
	if(message === undefined)
	{
		message = "No Default Message";	
	}
	for(var a = 0; a < times; a++)
	{
		console.log(message);
	}
}
printMessage(2);
Result No Default Message
No Default Message

See how simple it really is? All we did was create an if statement to check if the function call specified an argument message by seeing if it was equal to undefined. Since it was undefined, we went ahead and assigned our own value to the message variable. So when JavaScript finally saw us using the message variable, it didn’t think twice of wondering why it wasn’t specified in the function call.

References

JavaScript Quiz

The Standard JavaScript Quiz

JavaScript is one of the most powerful languages on the web because of it’s ability to reduce the workload placed on servers. The quiz is designed to determine if you have understand the fundamentals of JavaScript. Once you have mastered the basics, you should explore using JavaScript on your own for a little while. When you have finished tinkering with JavaScript, you might want to consider moving onto server side programming languages like PHP, and taking the PHP quiz.

Begin The JavaScript Quiz

JavaScript Tests and Exams

We currently only provide a standard JavaScript quiz that is not exactly a professional testing mechanism. However in the future, we might integrate a testing system into After Hours Programming, but we are not currently working towards that goal.