Types of Event Handlers

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.

functionChangeColor() {

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.

<!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">

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

<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.

 


Понравилась статья? Добавь ее в закладку (CTRL+D) и не забудь поделиться с друзьями:  



double arrow
Сейчас читают про: