Search results

JavaScript: Events and Listeners

Although you can start functions when your page loads, many times you'll want to start functions when a user clicks a link, enters a form, scrolls, moves his or her mouse over an object, or does something else. These actions are called events. You can set specific functions to run when the user performs an event. These functions "listen" for an event and then initiate the function.

Common Event Listeners

The following are common events:

onload //when the page loads
onclick //when a user clicks something
onmouseover //when a user mouses over something
onfocus //when a user puts the cursor in a form field
onblur //When a user leaves a form field

Note that each event listener begins with on and is entirely lowercase.

Adding Event Listeners

You can add an event listener directly in the HTML code in the following way:

<button onclick="alert('Hello, world');"></button>

However, mixing the JavaScript code with the HTML directly is generally a poor practice for the same reason that you don't integrate style commands into HTML but rather reference the styles in a separate CSS file.

A more common way to integrate the event listeners is by identifying the element and adding the event listener as a method. The general format for doing this is as follows:

myelement.onclick = function() {
//run your event handler code...
};

In this example, myelement would be a variable that refers to a specific style on your page.

Note that the word function is written without a name because its code is specified in the code block that immediately follows.

Also note that the statement ends with a semicolon ; after the closing curly brace }.

Associating Events with IDs

If you have a specific ID in your web page that uniquely identifies a section, you can associate an event with that ID. Here's an example:

//set a variable to refer to a specific ID
var specialSection = document.getElementById("specialSection");
//initiate this function when the user clicks the ID
specialSection.onclick = function() {
alert("Hello World")
};

Adding the addEventListener Method

You can also add event listeners using a method called addEventListener. However, this method isn't supported in Internet Explorer 8, so if you use this method, you need to add some conditional functions to check for browser functionality before running the function.

Some JavaScript libraries, like jQuery, automatically include checks for cross-browser functionality.

The format for adding events using this method is as follows:

document.addEventListener('click', myfunction, false);

In the above format, you start by adding the method to the Document object. In the parentheses, list the event listener but without the on. (In this example, the event listener is onclick, which is shortened to click.) You then add the function to run. (The function is declared elsewhere.) The false refers to an advanced, rarely used parameter for event handling.

Referencing Event Handlers

If your event handler refers to a specific element on the page, and you call your script before the element loads, the script won't work because the element isn't available at the time the script runs.

You could insert the script before the closing body tag to ensure the elements load first, but let's say you need your script to run earlier — before the element loads. You can use the prepareEventHandlers function to load the function when the page loads.

First, add the prepareEventHandlers function:

//declare the function
function prepareEventHandlers() {
//get a specific page ID and assign it as a variable
var specialSection = document.getElementById("specialSection");
//initiate this function when the ID is clicked
specialSection.onclick = function() {
alert("Hello World");
}
}

Now call the prepareEventHandlers function when the window loads:

window.onload = function() {
prepareEventHandlers();
}

Using this technique, the event will be loaded and ready even if it is referenced before the element it's listening for. Note that you can call the window.onload function only once per page.

onblur and onfocus Events

onblur and onfocus events refer to the way users interact with forms. When a user clicks a form field, an onfocus event occurs. When a user clicks out of the field, an onblur event occurs.

Here's an example. Let's say that your HTML form has an ID called namefield:

<input type="text" value="your name" name="name"
id="namefield" tabindex="10" />

First, get the namefield element, and then add an event to it.

//get the ID and assign it as a variable
var nameField = document.getElementbyId("name");
//when the ID is clicked, run this function
nameField.onfocus = function() {
//if the field has the value "your name", leave it blank
if ( nameField.value == "your name" ) {
nameField.value = "";
}
};

You can also add an onblur event to take place when the user leaves the field.

//get the ID and assign it as a variable
var nameField = document.getElementbyId("name");
//when the user leaves the ID, run this function
nameField.onblur = function() {
//if the field's value is "your name", don't write anything
if ( nameField.value == "your name" ) {
emailField.value = "";
}
};

Timers

You can add events that have a time delay. For example, if you want a pop-up message to appear after the user has been on the page for 10 seconds, you can do this through the setTimeOut method.

For example, let's say you have a simple message:

function welcomeVisitor() {
alert("Welcome to the site");
}

However, you don't want this message to appear until the user has been on the page for a while. You delay the action through the setTimeOut function:

setTimeOut(welcomeVisitor,8000);

The setTimeOut function has two parameters. The first allows you to call a function (which we declared earlier), and the second refers to the timer. The function will not be called for 8000 milliseconds.

There are other timer functions, such as setInterval, that initiate the function at the interval you specify.

About Tom Johnson

Tom Johnson

I'm an API technical writer based in the Seattle area. On this blog, I write about topics related to technical writing and communication — such as software documentation, API documentation, AI, information architecture, content strategy, writing processes, plain language, tech comm careers, and more. Check out my API documentation course if you're looking for more info about documenting APIs. Or see my posts on AI and AI course section for more on the latest in AI and tech comm.

If you're a technical writer and want to keep on top of the latest trends in the tech comm, be sure to subscribe to email updates below. You can also learn more about me or contact me. Finally, note that the opinions I express on my blog are my own points of view, not that of my employer.