28. Events


In This Chapter

Understand how communication happens between you and your app

Learn about events

Use event arguments to better handle event-related scenarios


In case you haven’t noticed, most applications and websites 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 you don’t start interacting with them:

Image

The reason for this is simple. Your applications exist to react to things that you do to them. They have some built-in motivation when you launch them to get themselves out of bed and ready for the day. Everything else that they do afterwards depends largely on what you tell them to do. This is where things get really interesting.

You tell your applications what to do by having them react to what are known as events. In this chapter, we will take an introductory look at what events are and how you can use them.

Onwards!

What Are Events?

At a high level, everything you create can be modeled by the following statement as shown in the following:

Image

You 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. The following are some examples of this statement filled out:

Image

This generic model applies to all of the code we’ve written together. This model also applies to all of the code your favorite developer/designer friends wrote for their applications. There is no way of escaping this model, so...there is no point in resisting. Instead, you 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 your keyboard. It could be your window getting resized. It could just be your document simply getting loaded. The thing to take away is that your signal could be one of hundreds of somethings that are built in to the JavaScript DOM API...or custom somethings that you created just for your app alone.

Getting back to our model, events make up the first half:

Image

Events define the thing that happens. They fire the signal. The second part of the model is defined by the reaction to the event:

Image

After all, what good is a signal if there isn’t someone somewhere that is waiting for it and then takes the appropriate action?! Okay, now that you 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 you with a lot of great support for working with them. To work with events, there are two things you 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 deep trauma JavaScript will inflict upon you if you 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 you do inside an application results in an event getting fired. Sometimes, your application will fire events automatically such as when it loads. Sometimes, your application will fire events as a reaction to you actually interacting with it. The thing to note is that your application is bombarded by events constantly whether you intended to have them get fired or not. Our task is to tell your 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 your application when an interesting event gets fired.

The way you use this function looks as follows:

source.addEventListener(eventName, eventHandler, useCapture);

That’s probably not very helpful, so let’s dissect what each part of this function means.

The Source

You call addEventListener via an element or object that you want to listen for events on. Typically, that will be a DOM element, but it can also be your document, window, or any other object that just happens to fire events.

The Event Name

The first argument you specify to the addEventListener function is the name of the event you are interested in listening to. The full list of events you have at your disposal is simply too large to list here (go to http://bit.ly/kirupaEvents instead), but some of the most common events you will encounter are shown in the following table.

Image

In subsequent chapters, we will look at a lot of these events in greater detail. For now, just take a quick glance at the click event, for we will be using that one in a few moments.

The Event Handler

The second argument requires you 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. You’ll learn a whole lot more about this function 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 you understand the implications of specifying either value, you are going to have to wait until the the next chapter where we talk about Event Bubbling and Capturing.

Putting It All Together

Now that you’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 you 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:

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 your 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() {
    // I am important!!!
}

Any code you place inside your event handler will execute when the event your addEventListener function cares about gets overheard. It’s all pretty simple!

A Simple Example

The best way to make sense of what we’ve learned so far is to see all of this actually working. To play along, add the following markup and code to an HTML file:

<!DOCTYPE html>
<html>
<head>
    <title>Click Anywhere!</title>
</head>
<body>
    <script>
        document.addEventListener("click", changeColor, false);

        function changeColor() {
            document.body.style.backgroundColor = "#FFC926";
        }
    </script>
</body>
</html>

If you preview your document in the browser, you will initially just see a blank page:

Image

Things will change when you click anywhere on the page, though. Once you’ve completed your click, your page’s background will change from white to a yellowish color:

Image

The reason for this is pretty easy to see. Let’s take a look at the code:

document.addEventListener("click", changeColor, false);

function changeColor() {
    document.body.style.backgroundColor = "#FFC926";
}

The addEventListener call is identical to what you saw earlier, so let’s skip that one. Instead, pay attention to the changeColor event handler:

document.addEventListener("click", changeColor, false);

function changeColor() {
    document.body.style.backgroundColor = "#FFC926";
}

This function gets called when the click event on the document is overheard. When this function gets called, it sets the background color of the body element to a shade of yellow. Tying this back to the very beginning where we generalized how applications work, this is what this example looks like:

Image

If all of this makes complete sense to you, then that’s great! You just learned about one of the most important concepts you’ll encounter. We aren’t done just yet. We let the event handler off the hook a little too easily, so let’s pay it one more visit.

The Event Arguments and the Event Type

Your event handler does more than just get called when an event gets overheard by an event listener. It also provides access to the underlying event object as part of its arguments. To access this event object easily, we need to modify your event handler signature to support this argument.

Here is an example:

function myEventHandler(e) {

    // event handlery stuff
}

At this point, your event handler is still a plain ol’ boring function. It just happens to be a function that takes one argument...the event argument! You can go with any valid identifier for the argument, but I tend to go with e because that is what all the cool kids do. There is nothing technically wrong with identifying your event as follows:

function myEventHandler(isNyanCatReal) {

    // event handlery stuff
}

Anyway, the event argument points to an Event object, and this object is passed in as part of the event firing. There is a reason why we are paying attention to what seems like a typical and boring occurrence. This Event object contains properties that are relevant to the event that was fired. An event triggered by a mouse click will have different properties when compared to an event triggered by your keyboard key press, a page load, an animation, and a whole lot more. Most events will have their own specialized behavior that you will rely on, and the event object is your gateway into all of that uniqueness.

Despite the variety of events and resulting event objects you can get, there are certain properties that are common. This commonality is made possible because all event objects are derived from a base Event type (technically, an Interface). Some of the popular properties from the Event type that you will use are as follows:

1. currentTarget

2. target

3. preventDefault

4. stopPropagation

5. type

To fully understand what these properties do, we need to go a little deeper into our understanding of events. We aren’t there yet, so just know that these properties exist. You’ll be seeing them real soon in future chapters.


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.107.152