Registering Events in JavaScript
 
 

Events are actions performed by the user such as clicking a button or hovering the mouse over a link. There are several events performed on an HTML page. You can override all of these events and use a custom JavaScript function to display feedback to the user. We've discussed some basic event handling, but you can also register event handlers with the JavaScript engine to handle more complex actions. These events can perform a simple change such as switching colors in a paragraph or returning values to the user depending on the element clicked. The results depend on what you want to do with your page, but the syntax is the same for most JavaScript code.

Registering Event Handlers

In previous lessons, we've used the inline HTML tag properties to override default event handlers. For instance, if we wanted to run a JavaScript function when the user clicks a button, we added a function name to the "onclick" property in the button's HTML code.

You can also register event handlers when you have more complex functions you want to hook to your HTML elements. The advantage of registering event handlers within the JavaScript code is that we can use the "this" statement. Instead of passing a value or element to the JavaScript function like we did in previous examples, we can leave out parameters and use "this" to manipulate properties for the element.

Registering events and hooking them to functions only takes one line of code. The following code registers and event to a button named "myButton."

myButton.onclick = ChangeColor;

Now, you define the function named "ChangeColor." Notice that you don't add the parenthesis to the button event handler registration. This is a part of the event handler registration process in JavaScript and other languages. If you add the parenthesis, the JavaScript engine things you are trying to run a function and assign a value to the onclick method.

The following code defines a JavaScript function that changes the background color for the button.

function ChangeColor() {

            this.style.backgroundColor = "#000000";

}

When a user clicks the button named myButton, the button's background color is changed to black, which is the color that corresponds with the hexadecimal value "#000000." Most designers need to look up color values when they assign font or background colors, but the two basic ones are black and white ("#FFFFFF"). You'll also notice that we used the "this" definition, which indicates that the button clicked is the one we want to change.

You can also use this type of event registration with multiple HTML elements. Using "this," you can change styles and properties without passing the element's name to the event handler. Take the following code as an example.

myButton.onclick = ChangeColor;

myOtherButton.onclick = ChangeColor;

The above code defines two buttons named "myButton" and "myOtherButton" and assigns the same event handler to the "onclick"button. Using the same function code, the "this" assignment points the function to the currently clicked button. This type of coding makes your code more dynamic and efficient, so you don't need to specify the button that is clicked for each element on your page.

Types of Event Handlers

We've focused mostly on the "onclick" event handler, but there are several more that you'll work with when you code in JavaScript.  This section will take a look at several of the other handlers available within the HTML code.

First, there is the "onload" and "unload" events. These two events trigger when a web page is loaded or unloaded in the browser. Usually, coders use the onload event to fire a JavaScript function. For instance, you might want to register events after a page loads in the browser. We've already created our function to change an element's background color, but we can call a function that registers each event when a page loads to make the website's code more efficient. Here is an example of a web page using the onload event.

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="mystyle.css">

<script> 

function RegisterEvents ( )
{
    clickme.onclick = ChangeStyle;

    username.onclick = ChangeStyle;
}

function ChangeStyle ( )
{
    this.style.backgroundColor = "#000000";
}

</script>

</head>

<body onload="RegisterEvents()" >

<div id="username"> Hi, user! </div>

<button id="clickme"> Click Me! </button>

</body>
</html>

The above code has two elements in its HTML. The first is a div named "username" and the second is a button named "clickme." We used the previous "ChangeStyle" function to register an event handler for the onclick action. Notice the "body" tag has the "onload" event added to its property definition. This event fires when the page loads, which then calls the function "RegisterEvents" to register event handlers for the two elements. When a user clicks these elements, the background color is changed to black ("#000000"). You can also use the "unload" event in the body tag to run functions when the user leaves a page or unloads it in the browser. 

We've covered some of the mouse events for JavaScript and HTML. There are four events that occur with a user mouse: onmouseover, onmouseout, onmousedown, onmouseup. The first two occur when the user hovers over an element and then moves the mouse away from the object. The second two occur when the user clicks the mouse button down and then release the button. When you change an attribute for the onmousedown event, you also need to change the style back to the original when the user releases the mouse button (onmouseup). The same is true for the onmouseover and onmouseout events. 

The following code gives you an example of the onmousedown and onmouseup events, which we haven't seen before. 

Interested in learning more? Why not take an online JavaScript course?

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="mystyle.css">

<script> 

function RegisterEvents ( )
{
    clickme.onmousedown = ChangeStyle;

    clickme.onmouseup = ChangeStyleBackToOriginal;
}

function ChangeStyle ( )
{
    this.style.backgroundColor = "#000000";
}

function ChangeStyleBackToOriginal ( )
{
    this.style.backgroundColor = "#FFFFFF";
}

</script>

</head>

<body onload="RegisterEvents()" >

<button id="clickme"> Click Me! </button>

</body>
</html>

The above code is different than the previous event handlers we've dealt with. Previously, we had one event handler for multiple objects that just changed the background color with a user clicked a button. We still use the same button, but this time the code is more granular with user input. Instead of a global "onclick" event handler, the above code includes a change in the background color when the user clicks the mouse button, and then it changes the background color back to white when the user releases the mouse button. The "this" directive is still used, so we separate the two event handler functions into two. 

You also have the option to pass the element to an event using the "this" statement in the function statement. Let's change the previous example's code just a little to give you an example. 

<!DOCTYPE html>
<html>

<head>

<link rel="stylesheet" type="text/css" href="mystyle.css">

<script> 

function ChangeStyle ( button )
{
    button.style.backgroundColor = "#000000";
}

function ChangeStyleBackToOriginal ( button )
{
    button.style.backgroundColor = "#FFFFFF";
}

</script>

</head>

<body >

<button id="clickme" onmousedown="ChangeStyle(this)" onmouseup="ChangeStyleBackToOriginal(this)"> Click Me! </button>

</body>
</html>

Notice we've removed the event handler registration function and replaced them with the inline definitions within the button's HTML code. You'll notice that now the event handler functions take a parameter named "button." In the HTML tag definition, the functions pass a variable named "this." The "this" directive tells the browser to pass the entire element as an object to the JavaScript function. When the JavaScript function gets the "this" directive variable, it can then manipulate the button object as a whole. In this example, the onmouseout and onmouseup events are hooked to the "clickme" button. Instead of using the implicit "this" statement within the function, the button element is passed to the function and the function uses the "button" parameter to change the button's styles. 

You can also use these functions multiple times in your code as long as you pass the functions an element to work with. Note that the variable name is "button," but you could also pass the function other elements such as a div, checkbox or paragraph. As long as the element has a "backgroundColor" style defined, the code lets you dynamically change any element's background color. You can even use the event handler function for other events such as onmouseout, onmousehover or onclick. 

Event handlers are a dynamic part of any web page. JavaScript event handlers can get complex, especially when you need to hook events to several elements on your page. If an event handler has a coding error, the user's browser will throw an error, so always test your code before you publish it to your production website.

Introduction to Ajax

We've looked at several ways you can use JavaScript in everyday scripts and dynamic HTML functions. JavaScript is an older language, and it's been an integral part of the web for several years. Because of its popularity, JavaScript has inspired developers to come up with libraries that make scripting easier. One such library and one of the earlier inspired asynchronous techniques is Ajax. Ajax stands for "asynchronous JavaScript and XML," which means it gives you a way to send commands to a web server while other processes load. This lesson with give you a quick example and overview of the Ajax library.

What is Ajax and Why Use It?

Ajax is a JavaScript library that you plug in to your HTML pages. Just like previous lessons used the "script" tag to link external JS files, Ajax is also an external library file you link to in your HTML pages. Ajax has expanded to several library versions that contain different functionality, so you might notice that some developers link to several Ajax files. 

In previous lessons, we loaded the web page and sent input from the user to a JavaScript function. The entire page sends back input to a server-side processing page and then returns the entire response page back to the user. With Ajax, input and response are asynchronous, which means that you don't need to send the entire page back to the server. At first you might wonder how this is an advantage over using simple JavaScript, but asynchronous calls are not only more convenient and user friendly, but they also take a processing load off of your server and save resources. 

A good example of Ajax benefits can come from the previous lesson. We had a select box that loaded options when the user clicked a radio button. What if we had several hundred options in a database and needed to load a subset based on user input. We can't put all of the options statically in a JavaScript function. This type of logic would become increasingly cumbersome and difficult to manage. Instead, we make a call to the web server that then calls the database for a list of options. What's the best way to do this? Using Ajax! 

Using the select drop-down example, Ajax lets you make a call to the web server in the background. The web page stays on the user's window, so it's invisible to the user. The user just sees a change in drop-down options after a radio box selection is made. This type of user interface is more convenient to the user and adds faster response times to your UI. Since user friendly interfaces can attract users, implementing Ajax is a benefit to your web pages especially when you have database intensive queries and front-end pages. 

Getting Started with Ajax

As we mentioned, Ajax libraries are linked to from the script tag. You can either host the Ajax files on your local server or link to them from a cloud server such as Google. Below is an example of linking an Ajax library to a file hosted on the local web server. 

<!DOCTYPE html>
<html>

<head>

<script type="text/javascript" src="jquery.min.js">

</script>

</head>

<body >

<div >
  This is where your Ajax content is shown.
</div>

</body>
</html>

Notice we added a "type" property to the script tag element. This lets the HTML engine know that you're linking an Ajax library. In this example, the linked library is jQuery, which is probably the most common Ajax library for making database calls to the web server asynchronously. 

We've also created a div tag with the default text "This is where your Ajax content is shown." This text is shown by default to the user, but you'll probably have a button or user input element that changes this content to something that matches the response from the user. For instance, you could have a button that displays content based on input from a web server. Again, the input is request asynchronously, so the page does not reload in the browser. Instead, the button makes a call to the JavaScript library and displays the response in the div element. Let's add this functionality to the previous HTML example. 

<!DOCTYPE html>
<html>

<head>

<script type="text/javascript" src="jquery.min.js">

</script>

<script type="text/javascript">

function displayValue (value)
{

 xmlhttp.open("POST","getName.php",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("userinput=" + value);

 var response=xmlhttp.responseText;

 document.getElementById("ajaxResponse").innerHTML = response;

            }

</script>

</head>

<body >

<div id="ajaxResponse" >
  This is where your Ajax content is shown.
</div>

<button type="button" onclick="displayValue('John')">Change It</button>

</body>
</html>

Normally, you would use a value that's dynamically entered by the user, but for this example, we pass a static value to the "displayValue" function. When the user presses the button, the value "John" is passed to the function that in turn passes the value to a php server processing page named "getName.php." Creating PHP code is beyond the scope of this lesson, but the input is taken as a form post in the PHP code. The PHP page sends back an HTML response to the JavaScript Ajax function and the result displays in the div we've named "ajaxResponse." The code also sets the request header, so the web server knows you're posting a form POST object when it sees the Ajax request. 

The xmlHttp variable contains the Ajax send and response containers. Incidentally, you can also use the form "GET" functionality that passes the value to the PHP processing page in the page's querystring. The way you use Ajax to pass variables depends on the PHP code in the processing page. Most processing pages use the form POST function, because the values don't display in the querystring and it's more secure. 

You might wonder what makes this code different from other JavaScript code, but the important advantage for Ajax versus regular JavaScript is the ability to send input to a processing page on the web server without reloading the entire page. When the user clicks the button, the page does nothing in the UI except call the PHP page. When the page is finished processing, the new text and HTML are displayed in the div. The look for the user is that the div's content changes immediately after clicking the button as if it happened on the front-end. This is especially useful when you have several HTML elements that require additional input before the full form can be processed. 

Using Ajax is similar to using JavaScript syntax, but it takes some time to get used to the way the asynchronous page calls work. Use this example to get started with dynamic content based on Ajax calls. You can also use JavaScript syntax within your Ajax functions, because Ajax is actually a JavaScript library. In other words, you can mix JavaScript and Ajax to create a fully function web page.