Events and Handling Them
This lesson is part of the Web Programming 1 Course.
Event driven programming allows you to invoke a function when a certain event occurs. An event can occur in many ways, for example when a user does something like clicking a button, scrolling the mouse wheel, or copying something from the web page into the clipboard. Events can also be things that are not necessarily triggered by a user, such as when a page finishes loading in the browser window. There are many events that you can 'hook into', which means that you can set up functions to be invoked when the event occurs.
To make use of event-driven programming in JavaScript, do the following:
- Define a function that you want to be invoked when a certain event occurs in your web page.
- Write code that 'hooks up' the function, so that it will get invoked when the event occurs.
Then, when the event occurs, the browser will invoke the function for you.
For this activity, create a file named event-handling.html and put this code into it:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Event Handling</title>
<script type="text/javascript">
</script>
</head>
<body>
<h1>Event Handling</h1>
<h2>Mouse Click Events</h2>
<input type="button" id="btn1" value="Button 1">
<br><br>
<input type="button" id="btn2" value="Button 2">
<input type="button" id="btn3" value="Button 3">
<br><br>
<h2>Mouse Move Events</h2>
Mouse Position X:<input type="text" size="3" id="txtPageX" />
<br/>
Mouse Position Y:<input type="text" size="3" id="txtPageY" />
</body>
</html>
<script>
// PUT YOUR JAVASCRIPT CODE HERE
</script>
Important Note:
If you look closely at the starter code above, you'll note that there are two script elements on the page. One is inside the head element, and the other is at the very bottom of the page. We'll start by putting our JavaScript code in the one that is at the bottom of the page. Then, later, we'll make use of the other script element (I'll explain when we get to that point).
Mouse Events
Using the mouse can trigger various types of events. A very common one occurs when the mouse is used to click a button on the web page. If you want to run some code when a button is clicked, there are a few different ways to do it, but in either case you will first need to 'get a handle' on the button (reminder: make sure to put this code inside the script element that is at the bottom of the web page):
const btn1 = document.getElementById("btn1");
Element objects that you extract from the DOM (like the one our btn1 variable has a handle on) have various properties that all begin with 'on'. So, if you want to invoke a function when the button is clicked, you could do it like so:
btn1.onclick = function(){
console.log("You clicked on btn1!");
}
In this example, we are assigning a function to the onclick property of the element object. When you run this code and click on the button, you'll see that the event will invoke the function. Functions that are used to when an event occurs are called event handler functions.
To 'hook into' mouse over events on the button, you can do this:
btn1.onmouseover = function(){
console.log("You moused over btn1!");
}
Here is a reference that shows other mouse events that you can hook into.
The addEventListener() Method
As mentioned, there is an alternative approach to hooking up event handler functions, and I recommend this approach because it allows you to do some things that cannot be done by assigning a function to an 'on' property.
Every element object has a method called addEventListener() which is designed for hooking up event handlers. Here's an example:
btn1.addEventListener("click", function(){
alert("You clicked on btn 1!")
});
The addEventListener() method is an extremely important one that you will use a lot in JavaScript. Because of the name of this method, many programmers would describe the code sample above by saying 'listening' for click events to occur on btn1.
Here is an explanation of the parameters that you must pass into it:
- The first parameter is a string, which is the name of the event you want to 'listen' for.
- The second parameter is a function, which is the event handler that will be invoked by the browser detects the event.
Anonymous Functions (and 'Named' Functions)
If you take a look at the previous code samples you'll notice that the event handler functions do not have names. These are known as anonymous functions and they are quite common in JavaScript. Up until this point we have always specified a name for a function when we declare it. These are known as named functions. You could use a named function as an event handler, which can be handy if you want to use the exact function for handling multiple events. Consider this example:
// Declare a 'named' function
function clickHandler(){
console.log("You clicked on a button!!!");
}
// Get a handle on the buttons
const btn2 = document.getElementById("btn2");
const btn3 = document.getElementById("btn3");
// Hook up the function by using the 'onclick' property
btn2.onclick = clickHandler;
// Hook up the function by using addEventListener()
btn3.addEventListener("click", clickHandler);
It's important to note that both btn2 and btn3 are using using the exact same function for the event handler. This is because the event handler has a name (clickHandler) that can be used to refer to it. When an anonymous function is used, it can only be used in one place because it has no name and there is no way to refer to it other than where it is declared.
It's also important to note that the last two statements in the above code sample do NOT include the parenthesis after the name of the function. We simply use the name of the function when we hook it up to listen for click events on the two buttons. The reason for this, is that if we included the parenthesis then the functions would be invoked immediately when the statement executes. The intention with event handler functions is that they be called later, when the event actually occurs. The browser will keep track of all the event handlers that you hook up in your code, and the browser will invoke the function when the event occurs. If you add the parenthesis after 'clickHandler' in the last two statements, you'll see in the console log that the clickHandler function will be invoked 2 times when you reload the page, which is not what we want (we want the function to be invoked when the 'click' event occurs on the buttons, not when the page loads). So if you use named functions as your event handlers, then be careful not to include the parenthesis when you hook them up.
Because event handler functions are meant to be 'called later', when a specific event occurs, they are often referred to as callback functions.
Window 'load' Events
So far have been focusing on 'mouse' events. There are many categories of events that you can use that will make your web page do all sorts of interesting things (and we'll explore them in the next course). But there is one in particular that we need to address right now.
If you move all the JavaScript code we have written so far from the bottom script element to the one that is inside the head element, you'll find that the code will crash when you refresh the page. The problem is that the code tries to 'get handles' on the buttons before they have loaded. When a page loads, the browser will read (interpret) the code from the top down. So if your JavaScript code refers to a button before the button has been loaded, then things will go wrong.
To avoid this problem, you can wait until the page has fully loaded in the browser window. Only after this event occurs will it be safe to 'get handles' on any of the HTML elements in the page. You can 'listen' for the window's 'load' event like so:
window.addEventListener("load", function(){
// PUT ALL OF YOUR JAVASCRIPT CODE HERE
});
Go ahead and paste this code sample into the first script element in your sample page. And then put all the rest of the JavaScript code we have written inside the event handler.
I've been waiting to tell you about the window's 'load' event for a long time because it's a standard practice to wait for this event to occur before executing any of your JavaScript code.
Fun with Events
We've talked about 'mouse' events by hooking up event handlers to buttons. Now I want to show you something cool that you can do by listening for mouse 'move' events in the window.
Put this code under your other JavaScript code (but inside the event handler function that listens for the window to load):
const txtPageX = document.getElementById("txtPageX");
const txtPageY = document.getElementById("txtPageY");
window.addEventListener("mousemove", function(evt){
txtPageX.value = evt.pageX;
txtPageY.value = evt.pageY;
});
If you run the code and move your mouse around the browser window, you'll see that the mouse coordinates are being tracked inside the text boxes.
The event handler function in this code declares a parameter named evt which is one that we will be exploring in the beginning of the Web II class. We'll also be exploring many other types of events.