What is an event handling in javascript?
HTML events are "things" that happen to HTML elements. Show
When JavaScript is used in HTML pages, JavaScript can "react" on these events. HTML EventsAn HTML event can be something the browser does, or something a user does. Here are some examples of HTML events:
Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. With single quotes: With double quotes: In the following example, an ExampleTry it Yourself » In the example above, the JavaScript code changes the content of the element with id="demo". In the next example, the code changes the content of its own element (using ExampleTry it Yourself » JavaScript code is often several lines long. It is more common to see event attributes calling functions: Common HTML EventsHere is a list of some common HTML events:
The list is much longer: W3Schools JavaScript Reference HTML DOM Events. JavaScript Event HandlersEvent handlers can be used to handle and verify user input, user actions, and browser actions:
Many different methods can be used to let JavaScript work with events:
You will learn a lot more about events and event handlers in the HTML DOM chapters. Test Yourself With ExercisesExercise:The Start the Exercise 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. For example, in an airport, when the runway is clear for take off, a signal is communicated to the pilot. As a result, the plane can safely take off.
In the case of the Web, 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 these
You 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 bubbling and captureEvent bubbling and capture are terms that describe phases in 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: This makes sense: the button is inside the What 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: 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 section, we'll see a problem that it causes, and find the solution. Open up the
show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below: This example shows and hides a
When the We then add a couple more Now, when the area of the But there's a problem — currently, when you
click the video it starts to play, but it causes the When an event is fired on an element that has parent elements (in this case, the In the capturing phase: In the target phase: In the bubbling phase, the exact opposite of the capturing phase occurs: In modern browsers, by default, all event handlers are registered for the bubbling phase. So in our current example, when you click the video, the event bubbles from the Note: All JavaScript events go through the capturing and target phases. Whether an event enters the bubbling phase can be checked by the read-only Note: Event listeners registered for the The following example demonstrates the behavior described above. Hover over the numbers and click on them to trigger events, and then observe the output that gets logged. As we saw in the video
example, this can be a very annoying behavior, but there is a way to prevent it! The standard So we can fix our current problem by changing the second handler function in the previous code block to this: You can try making a local copy of the show-video-box.html source code and fixing it yourself, or looking at the fixed result in
show-video-box-fixed.html (also see the source code here). Note: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible
than they are 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 the one modern browsers implemented. Note: As mentioned above, by default almost all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the
capturing phase instead, you can do so by registering your handler using Event bubbling isn't just annoying though: it can be very useful. In particular, it enables a practice called 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 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. You
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. |