Breadcrumbs

Too Easy JavaScript - Event Handlers [7]

Hooking code to events is an important aspect that makes JavaScript such a powerful browser scripting language. Event handlers allow you to set up code to run when a particular event is executed. Making your code fire in response to user actions escalates your website to a whole new level.

The following code will only work properly in Firefox (external link) (and other Gecko based browsers) and Opera (external link). Both Safari and Internet Explorer have an obscure way of dealing with DOM event handlers, and therefore will not be covered in this lesson.

Events The Old Way

Long ago web developers polluted their markup with event attributes to trigger JavaScript code. Using the old method, there is a separate attribute for each event, which makes JavaScript intermix even more with the HTML markup.

Code: JavaScript

function linkClicked() {
    alert("A link was clicked!");
}

Code: XHTML

<a href="http://www.lowter.com" onclick="linkClicked()">Link</a>

When the action is performed, which in this case is when the link is clicked, the set function will run. The only advantages to the old method are that everything is pretty no-nonsense and that people are extremely use to it. The disadvantages are that there is no separation between the HTML and the JavaScript and that the W3C DTD files do not support the countless event attributes, which will cause your markup to be invalid.

The New Way

JavaScript has evolved over the ages and has moved towards an unobtrusive model. Developers are now able to completely separate their JavaScript from the rest of their code. Event handlers allow you to set up events without even modifying the document's markup.

The DOM method of event handling involves event targets, the element(s) that the event is assigned to, and event listeners, the function that responds to the triggered event.

Event handlers start with event listeners. To add an event listener we use the addEventListener() function:

Code: JavaScript

addEventListener(eventType, fn, false);

The first parameter (eventType) holds the type of event the listener is "listening" for. The second parameter (fn) holds the function that will run when the event is triggered. The last parameter is for event capturing, which you can leave as false. You apply event listeners to element references.

Event bubbling and event capturing are both topics that involve the order of event execution (external link), and are rarely required by developers. They will not be covered in this lesson and will not affect any of the examples provided here.

Code: JavaScript

function linkClicked() {
    alert("A link was clicked!");
}

var link = document.getElementById("link");
link.addEventListener('click', linkClicked, false);

Code: XHTML

<a href="http://www.lowter.com" id="link">Link</a>

Above, first we declare a small function that will handle the triggered event. Then we declare a reference to the link element in our markup. Last, we add a click event to the link, using our previously established reference. When the link is clicked the linkClick() function will run, before the linked page has loaded. As you can see, the DOM method for event handling requires no interference with the page's markup.

Reacting To Events

Now that you know how to set up an event handler, you need to learn how to respond to triggered events. When an event is triggered its event listener will run the specified function. By setting up the function to accept an argument, e, you can respond more to events.

Code: JavaScript

function linkClicked(e) {
    
}

From this argument you can access properties that contain information about the event:

Property Description
target Element that fired the event.
type Type of event.
button Mouse button that was pressed - left (0), middle (1), or right (2).
keyCode Character code of the pressed key.

The main property you will use is target, allowing you to manipulate the triggering element via the Document Object Model.

Code: JavaScript

function linkClicked(e) {
    var target = e.target;
    target.style.color = "green";
}

var link = document.getElementById("link");
link.addEventListener('click', linkClicked, false);

Code: XHTML

<a id="link">Link</a>

In the above code, we create a reference to the target element and change the color of the text to green. Passing the event's information into the triggered function allows you to work full-heartedly with the element(s) in a portable environment. With ease, we could formulate this same code on different elements, showing how the new event handling method is also more portable.

Stopping Default Actions

In some situations you may need to stop the default actions of an element, such as blocking a hyperlink from loading the linked page. To do this you use the preventDefault() function of the e argument.

Code: JavaScript

function linkClicked(e) {
    e.preventDefault();
}

Event List

JavaScript has a variety of event types that can be used to trigger code:

Event Element(s)
load window
unload window
change input, select, textarea
focus label, input, select, textarea
blur label, input, select, textarea
submit form
mouseover all
mouseout all
mousedown all
mouseup all
click all
dblclick all
keypress all that can receive the focus

Note: Don't apply click and dblclick event listeners to the same element, as they will tie themselves into a knot.

Note: This issue only applies when you serve your markup in the text/html MIME type.

Loading Event Listeners

One of the issues with event listeners and the DOM is that in order for them to work properly the elements have to be already declared. Otherwise, there is nothing for either of them to work with. The solution lies within the load event of the window.

To bypass this dilemma, you create an extra function that will load your needed event listeners, which will be triggered by the window's loading event:

Code: XHTML

<html>
    <head>
        <script type="text/javascript">
            function linkClicked(e) {
                var target = e.target;
                target.style.color = "green";
            }
            
            function addListeners() {
                var link = document.getElementById("link");
                link.addEventListener('click', linkClicked, false);
            }
            
            window.addEventListener('load', addListeners, false);
        </script>
    </head>
    <body>
        <a id="link">Link</a>
    </body>
</html>

Compared to our previous code, we placed our event listener declarations in the addListeners() function. Then we set up the function to run upon the loading of the window, assuring us that the DOM will be completely loaded.

Summary

In Part 7 of Too Easy JavaScript, you learned how to make your code respond based on user triggered events. You learned how to set up event listeners, gather an event's information, stop default element actions, and properly load event listeners in HTML. In Part 8 we will dive deeper into the Document Object Model, learning how to manipulate a page's DOM tree even more.