Events in JavaScript by kirupa (https://www.kirupa.com/me/index.htm) | filed under JavaScript 101 (https://www.kirupa.com/javascript/learn_javascript.htm) In case you haven't noticed, most applications and web sites are pretty boring when left alone. They launch with great fanfare and gusto, but the excitement they bring to the table goes away very quickly if we don't start interacting with them: [Image: can we go home?] (https://www.kirupa.com/html5/images/boring_72.png) The reason for this is simple. Our applications exist to react to things that we do to them. They have some built in motivation when we launch them to get themselves out of bed and ready for the day. Everything else that they do afterwards depends largely on what we tell them to do. This is where things get really interesting. The way we tell our applications what to do is by having them react to what are known as events. In this tutorial, we will take an introductory look at what events are and how we can use them. Onwards! What are Events? At a high-level, everything we create can be modeled by the following statement: [Image: when something happens] (https://www.kirupa.com/html5/images/when_1_72.png) We can fill in the blanks in this statement in a bajillion different ways. The first blank calls out something that happens. The second blank describes the reaction to that. Here are some examples of this statement filled out: [Image: examples] (https://www.kirupa.com/html5/images/example_apps_72.png) This generic model applies to all of the code we've written together. This model also applies to all of the code our favorite developer/designer friends wrote for their applications. There is no way of escaping this model, so...there is no point in resisting. Instead, we need to learn to embrace the star of this model, the very talented critter known as the event. An event is nothing more than a signal. It communicates that something has just happened. This something could be a mouse click. It could be a key press on our keyboard. It could be our window getting resized. It could just be our document simply getting loaded. The thing to take away is that our signal could be any hundreds of somethings that are built-in to the JavaScript language...or custom somethings that we created just for our app alone. Getting back to our model, events make up the first half: [Image: where events fit into all of this] (https://www.kirupa.com/html5/images/event_half_72.png) An event defines the thing that happens. It fires the signal. The second part of the model is defined by the reaction to the event: [Image: reaction] (https://www.kirupa.com/html5/images/react_half_72.png) After all, what good is a signal if there isn't someone somewhere that is waiting for it and then takes the appropriate action?! Ok - now that we have a high level overview of what events are, let's dive into how events live in the nature reserve known as JavaScript. Events and JavaScript Given the importance of events, it should be no surprise to you that JavaScript provides us with a lot of great support for working with them. To work with events, there are two things we need to do: 1. Listen for events 2. React to events These two steps seem pretty simple, but never forget that we are dealing with JavaScript here. The simplicity is just a smokescreen for the depth of the trauma JavaScript will inflict upon us if we take a wrong step. Maybe I am being overly dramatic here, but we'll find out soon enough. 1. Listening for Events To more bluntly state what I danced around earlier, almost everything we do inside an application results in an event getting fired. Sometimes, our application will fire events automatically...such as when it loads. Sometimes, our application will fire events as a reaction to us actually interacting with it. The thing to note is that our application is bombarded by events constantly whether we intended to have them get fired or not. Our task is to tell our application to listen only to the events we care about. The thankless job of listening to the right event is handled entirely by a function called addEventListener. This function is responsible for being eternally vigilant so that it can notify another part of our application when an interesting event gets fired. The way we use this function looks as follows: source.addEventListener(eventName, eventHandler, false); That's probably not very helpful, so let's dissect what each part of this function means. The Source We call addEventListener via an element or object that we want to listen for events on. Typically, that will be a DOM element, but it can also be our document, window, or any object specially designed to fire events. The Event Name The first argument we specify to the addEventListener function is the name of the event we are interested in listening to. The full list of events we have at your disposal is simply too large to list here (go here instead (http://www.w3.org/TR/DOM-Level-3-Events/#events-module)), but some of the most common events you will encounter are: In subsequent tutorials, we will look at a lot of these events in greater detail. For now, just take a quick glance at the click event. We will be using that one in a few moments. The Event Handler The second argument requires us to specify a function that will get called when the event gets overheard. This function is very affectionately known as the event handler by friends and family. We'll learn a whole lot more about this function (and occasionally an object) in a few moments. To Capture, or Not to Capture, That Is the Question! The last argument is made up of either a true or a false. To fully help us understand the implications of specifying either value, we are going to have to wait until the the Event Bubbling and Capturing in JavaScript (https://www.kirupa.com/html5/event_capturing_bubbling_javascript.htm) tutorial. This tutorial happens to be next in this series, so we won't be waiting long. Putting It All Together Now that we've seen the addEventListener function and what it looks like, let's tie it all up with an example of this function fully decked out: document.addEventListener("click", changeColor, false); Our addEventListener in this example is attached to the document object. When a click event is overheard, it calls the changeColor function (aka the event handler) to react to the event. This sets us up nicely for the next section which is all about reacting to events. 2. Reacting to Events As we saw in the previous section, listening to events is handled by addEventListener. What to do after an event is overheard is handled by the event handler. I wasn't joking when I mentioned earlier that an event handler is nothing more than a function or object: function normalAndBoring() { // I like hiking and puppies and other stuff! } The only distinction between a typical function and one that is designated as the event handler is that our event handler function is specifically called out by name in an addEventListener call (and receives an Event object as its argument): document.addEventListener("click", changeColor, false); function changeColor(event) { // I am important!!! } Any code we place inside our event handler will execute when the event our addEventListener function cares about gets overheard. A Simple Example The best way to make sense of what we've learned so far is to see all of this fully working. To play along, add the following markup and code to an HTML document: