Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

JavaScript Events - Introduction

Chapter 58 12 mins

Learning outcomes:

  1. What are events
  2. The history of events in JavaScript
  3. What we'll cover in this unit

Introduction?

JavaScript is an astoundingly powerful language, driving the modern-day frontend of the web. Part of this lies in the fact that it comes equipped with a whole ecosystem of events that allows us to handle given actions.

The actions can be initiated by the user and be as simple as a mouse click, a key press, or a touch gesture. They can even be browser-initiated, such as completing the loading of a particular resource.

When we say that JavaScript makes a web page 'interactive', it is precisely this ecosystem of events that enables all that interactivity in the first place.

In this unit, we'll devote all our attention to learning how exactly to work with events in JavaScript. We'll start by understanding what exactly are events; how browsers fire them; how to handle given events occuring on given targets; and a plethora of other related notions such as event propagation, event cancellation, the event loop, custom event dispatching, and so on and so forth.

To be able to produce high-quality web applications, understanding events in JavaScript is of utmost importance. And the best part is that learning about them is really simple and fun. In fact, once you are done with events, you'll be able to create much more amazing JavaScript programs and, likewise, enjoy coding in it, a lot!

There are endless possibilities of applications awaiting you!

What are events?

Let's start with the most basic idea — what exactly is meant by an 'event'?

Well, technically speaking:

An event is an action occuring on a web page.

As we stated previously, the action can be initiated either by the user or by the browser itself.

For instance, suppose a user clicks a button on a web page. Here the event is the 'clicking' action made by the user. Similarly, when the browser completes the download of a given resource, it might notify the JavaScript engine of this fact. And once again, we have an event — the completion of the resource's download — this time initiated by the browser itself.

In short, whatever the case be, an event is just an action.

Now how many such actions could you think about, that a user or the browser could initiate while he/she is using a web page?

To give you a headstart, the user can press a key on the keyboard, play an audio element, switch to fullscreen mode, and... Try writing all your ideas on a piece of paper.

Well, there are literally tons and tons of actions that can potentially be made on a web page. And that's why the events ecosystem provided in JavaScript is so huge — there is just so much to cover!

Below we try to briefly list just 1% of all the possible actions that could be initiated in JavaScript:

  • Clicking a given element.
  • Playing an <audio> or <video>.
  • Going to full screen.
  • Hovering the mouse pointer over an element.
  • Right-clicking on the web page.
  • Copying the text inside an <input> element.
  • Scrolling the web page.
  • Dragging a file into the web page.
  • Changing the hash of the URL.

...and so on.

Each of the actions listed above represents something to which the underlying web page can sensibly respond to.

For instance, when the data inside a password field is copied (let's say by pressing Ctrl + C), the program could react by denying that action and rather getting the user to manually retype the password in the 'Confirm password' field.

Similarly, when an image is dragged from the OS home page into the browser window, inside a given element, we could react by reading the image file and then displaying a preview of it. This is very common in applications out there.

As another example, when the web page is scrolled beyond a certain point, we could react by sticking a particular within the viewport. This is often referred to as 'sticky positioning' and is also quite common across the web.

As we shall see later on, the Events API in JavaScript provides events for all the aforementioned and the remaining 99% actions, and likewise allows us to respond with given pieces of code, as appropriate, when either of them occurs.

Some events in this gigantic API are remnants of the legacy era of JavaScript, i.e. the late 90s; some are relatively-recent introductions to the browser environment; while some are still in the process of standardization.

Anyways, so now that we know the very basic meaning of an 'event', it's time to dig deeper into it, in the context of JavaScript code.

Back in time with events

Events were first introduced into JavaScript with the advent of Netscape Navigator 2.0 and Internet Explorer 3, in 1995. Back in the day, the sole purpose of providing events and event-handling capabilities in this rudimentary scripting language was to simplify certain tasks that were otherwise being offloaded to the backend server.

The best example of this would be form validation. For a very long time, form validation, even as trivial as checking whether a field wasn't left empty, was all done on the server. However, with JavaScript it was conceived that such a trivial task could well easily be done on the client-end.

What do you think about this?

The number of events provided in the language during these early times was pretty small, with very few features given to developers while handling them. However, remember that an event loop was used from the very beginning in order to effectively handle these events.

We'll learn about the event loop in detail in the next chapter.

Eventually, as this idea of events in JavaScript proved to be useful — in fact, extremely useful — soon it found its way into the W3C DOM standard.

The DOM Level 2 standard, published in 2000, with its Events specification, formalized the notion of events in JavaScript. Although events had been in use for almost half a decade, this was the first-ever formal specification to introduce a unified API for them.

At this point, it's worth noting that the very-first event model used by Navigator 2.0 and Internet Explorer 3 was pretty successful and continues to be supported to date in all browsers. It is regarded as a part of the legacy DOM (recall the legacy DOM from the HTML DOM unit?) and for backwards-compatilibity was also included in the DOM Level 2 standard.

As we shall see in the next chapter, the legacy DOM's event model is really simple to understand and work with. However, at the same time, it has certain downsides due to which a new mechanism of working with events (the EventTarget interface) was proposed and thereby standardized by W3C in the same DOM Level 2 standard.

Today, at the time of this writing, the Events API is all: humongous, mature, and simple. We have tons and tons of events in the language, ultimately making tons and tons of parts of the computer accessible to the end JavaScript developer.

Where this gives developer a lot more power and freedom, it also makes the entire events ecosystem increasingly complex. So we, as developers, need to put in the effort to learn the ecosystem the right way and leverage its real potential.

In this unit

It's now time to discuss on what exactly we'll be learning in the subsequent chapters of this unit.

Starting with the next chapter, JavaScript Events — Basics, we'll see what are event types and targets and how to use these two ideas to handle events occuring on given objects in the web page.

We'll also discover the EventTarget interface and its two most frequently-used methods addEventListener() and removeEventListener() used to set up event handlers.

Not only this, but we'll also see a couple of ways to set up event handlers, i.e. by using JavaScript event-handling properties, or the EventTarget interface, or the HTML event-handling attributes.

Then in the next-to-next chapter, JavaScript Events — Event Objects, we'll move our attention to consider event objects, i.e. objects sent as arguments into event handlers, carrying useful information regarding the event such as where it occured on the screen, or on which element, and so on. We'll also see a couple of interfaces designed for such objects and their hierarchy.

Moving on, in the chapter JavaScript Events — Event Propagation, we'll understand what exactly is meant by propagation of events and how it's utilized by browsers to determine which objects further downstream or upstream in the DOM tree to take into account while dispatching a given event.

There are mainly two ways of propagation: the legacy capturing and then the more sensible and default approach of bubbling. We'll unravel the working of both these ways in detail in that very chapter.

Once all these basic foundational ideas of events are covered, we'll then start discussing about specific events and how to handle them.

Here, we'll begin with the very basic mouse events, then progressing to keyboard events, then to the scroll event, then to load events and findally ending with URL-based events, in particular the hash change and the popstate events.

After this, we'll dedicate whole units to specific kinds of events by virtue of being extremely complex to handle and work with, in general. These kinds include touch events, form-related events, and drag events.

We'll create numerous programs, ranging from pretty simple to fairly complicated ones, using all of the ideas learnt in the unit and thus make the whole voyage of learning events a joyous one.

So, let's get going.