Events are actions or occurrences that happen in the system you are programming, which the system tells you about so your code can react to them. For example, if the user clicks a button on a webpage, you might want to react to that action by displaying an information box. In this article, we discuss some important concepts surrounding events, and look at how they work in browsers. This won't be an exhaustive study; just what you need to know at this stage. A series of fortunate eventsAs mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs. Events are fired inside the browser window, and tend to be attached to a specific item that resides in it. This might be a single element, a set of elements, the HTML document loaded in the current tab, or the entire browser window. There are many different types of events that can occur. For example:
You can gather from this (and from glancing at the MDN event reference) that there are a lot of events that can be fired. To react to an event, you attach an event handler to it. This is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are registering an event handler. Note: Event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening. Note: Web events are not part of the core JavaScript language — they are defined as part of the APIs built into the browser. A simple example Let's look at a simple example of what we mean here. In the following example, we have a single
The JavaScript looks like so:
In this code, we store a reference to the We also define a function that returns a random number. The third part of the code is where we define and register the event handler. The
The example output is as follows. Try clicking the button: It's not just web pagesEvents are not unique to JavaScript — most programming languages have some kind of event model, and the way the model works often differs from JavaScript's way. In fact, the event model in JavaScript for web pages differs from the event model for JavaScript as it is used in other environments. For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications. The Node.js event model relies on listeners to listen for events and emitters to emit events periodically — it doesn't sound that different, but the code is quite
different, making use of functions like You can also use JavaScript to build cross-browser add-ons — browser functionality enhancements — using a technology called
WebExtensions. The event model is similar to the web events model, but a bit different — event listeners' properties are camel-cased (such as You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments. Using addEventListener()The recommended mechanism for
adding event handlers in web pages is the
Inside the It is fine to make the handler function a separate named function, like this:
Listening for other eventsThere are many different events that can be fired by a button element. Let's experiment. First, make a local copy of
random-color-addeventlistener.html, and open it in your browser. It's just a copy of the simple random color example we've played with already. Now try changing
Some events, such as Removing listenersIf you've added an event handler using
Event handlers can also be removed by passing an
Then the event handler created by the code above can be removed like this:
For simple, small programs, cleaning up old, unused event handlers isn't necessary, but for larger, more complex programs, it can improve efficiency. Also, the ability to remove event handlers allows you to have the same button performing different actions in different circumstances: all you have to do is add or remove handlers. Adding multiple listeners for a single eventBy making more than one call to
Both functions would now run when the element is clicked. Learn moreThere are other powerful features and options available with These are a little out of scope for this article, but if you want to read them, visit the
Other event listener mechanismsWe recommend that you use Event handler properties Objects (such as buttons) that can fire events also usually have properties whose name is For example, we could rewrite the random-color example like this:
You can also set the handler property to a named function:
With event handler properties, you can't add more than one handler for a single event. For example, you can call
This is impossible with event handler properties because any subsequent attempts to set the property will overwrite earlier ones:
Inline event handlers — don't use theseYou might also see a pattern like this in your code:
The earliest method of registering event handlers found on the Web involved event handler HTML attributes (or inline event handlers) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined
inside a
You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are doing something really quick, but they quickly become unmanageable and inefficient. For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to read. Keeping your JavaScript separate is a good practice, and if it is in a separate file you can apply it to multiple HTML documents. Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:
Finally, many common server configurations will disallow inline JavaScript, as a security measure. You should never use the HTML event handler attributes — those are outdated, and using them is bad practice. Event objects Sometimes, inside an event handler function, you'll see a parameter specified with a name such as
Here you can see we are including an event object, e, in the function, and in the function setting a background color style on Note: See the
Event delegation section below for an example where we use Note: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. Most event objects have a standard set of properties and methods available on the event object; see the Some event objects add extra properties that are relevant to that particular type of event. For example,
the
Try typing into the text box and see the output: Preventing default behaviorSometimes, you'll come across a situation where you want to prevent an event from doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and click the submit button, the natural behavior is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified). The trouble comes when the user has not submitted the data correctly — as a developer, you want to prevent the submission to the server and give an error message saying what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example. First, a simple HTML form that requires you to enter your first and last name:
Now some JavaScript — here we implement a very simple check inside a handler for the
Obviously, this is pretty weak form validation — it wouldn't stop the user from validating the form with spaces or numbers entered into the fields, for example — but it is OK for example purposes. The output is as follows: Event bubblingEvent bubbling describes how the browser handles events targeted at nested elements. Setting a listener on a parent elementConsider a web page like this:
Here the button is
inside another element, a
You'll see that the parent fires a click event when the user clicks the button: You clicked on a DIV element This makes sense: the button is inside the Bubbling exampleWhat happens if we add event listeners to the button and the parent?
Let's try adding click event handlers to the button, its parent (the
You'll see that all three elements fire a click event when the user clicks the button: You clicked on a BUTTON element You clicked on a DIV element You clicked on a BODY element In this case:
We describe this by saying that the event bubbles up from the innermost element that was clicked. This behavior can be useful and can also cause unexpected problems. In the next sections, we'll see a problem that it causes, and find the solution. Video player exampleIn this example our page contains a video, which is hidden initially, and a button labeled "Display video". We want the following interaction:
The HTML looks like this:
It includes:
We're using CSS to hide elements with the
The JavaScript looks like this:
This adds three
Let's see how this works: You should see that when you click the button, the box and the video it contains are shown. But then when you click the video, the video starts to play, but the box is hidden again! The video is inside the Fixing the problem with stopPropagation() As we saw in the last section, event bubbling can
sometimes create problems, but there is a way to prevent it. The We can fix our current problem by changing the JavaScript to this:
All we're doing here is calling
Event captureAn alternative form of event propagation is event capture. This is like event bubbling but the order is reversed: so instead of the event firing first on the innermost element targeted, and then on successively less nested elements, the event fires first on the least nested element, and then on successively more nested elements, until the target is reached. Event capture is disabled by default. To enable it you have to pass the This
example is just like the bubbling example we saw earlier, except that we have used the
In this case, the order of messages is reversed: the You clicked on a BODY element You clicked on a DIV element You clicked on a BUTTON element Why bother with both capturing and bubbling? In the bad old days, when browsers were much less cross-compatible than now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is what modern browsers implement. By default almost all event handlers are registered in the bubbling phase, and this makes more sense most of the time. Event delegationIn the last section, we looked at a problem caused by event bubbling and how to fix it. Event bubbling isn't just annoying, though: it can be very useful. In particular, it enables event delegation. In this practice, when we want some code to run when the user interacts with any one of a large number of child elements, we set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Let's go back to our first example, where we set the background color of the whole page when the user clicked a button. Suppose that instead, the page is divided into 16 tiles, and we want to set each tile to a random color when the user clicks that tile. Here's the HTML:
We have a little CSS, to set the size and position of the tiles:
Now in JavaScript, we could add a click event handler for every tile. But a much simpler and more efficient option is to set the click event handler on the parent, and rely on event bubbling to ensure that the handler is executed when the user clicks on a tile:
The output is as follows (try clicking around on it): Note:
In this example, we're using Test your skills!You've reached the end of this article, but can you remember the most important information? To verify you've retained this information before you move on — see Test your skills: Events. ConclusionYou should now know all you need to know about web events at this early stage. As mentioned, events are not really part of the core JavaScript — they are defined in browser Web APIs. Also, it is important to understand that the different contexts in which JavaScript is used have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all of these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development. If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help. See also
In this moduleWhat happens when you click the replace all button?What happens when you click the Replace All button? All occurrences of that text in the document are replaced.
Which of the following actions will select the entire document?Press Ctrl+A on your keyboard to select all text in the document.
In which two locations can you change the username that appears in the track changes listing?Change the user name and/or the initials in the Word Options dialog box. Pro Tip: You can also open the Word Options dialog box by selecting the File Tab followed by Options in the backstage view.
Which of the following is the correct keyboard shortcut for applying bold formatting?Click Bold. in the Font group on the Home tab. Type the keyboard shortcut: CTRL+B.
|