JavaScript: Events and Listeners
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 it's code is specified in the code block that immediately follows.
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
const 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.
The format for adding events using this method is as follows:
document.addEventListener('click', myFunction)
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
const 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" placeholder="your name" name="name"
id="namefield" />
First, get the namefield element, and then add an event to it.
//get the ID and assign it as a variable
const 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
const 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.
These were some simple examples and there's a lot more to learn, you can check the MDN to get more information.
Top comments (0)