Movatterモバイル変換


[0]ホーム

URL:


  1. Learn
  2. Core learning modules
  3. JavaScript
  4. Events

Introduction to events

Events are things 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 the fundamentals of how they work in browsers.

Prerequisites:An understanding ofHTML and thefundamentals of CSS, familiarity with JavaScript basics as covered in previous lessons.
Learning outcomes:
  • What events are — a signal fired by the browser when something significant happens, which the developer can run some code in response to.
  • Setting up event handlers usingaddEventListener() (andremoveEventListener()) and event handler properties.
  • Inline event handler attributes, and why you shouldn't use them.
  • Event objects.

What is an event?

Events are things 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:

  • The user selects, clicks, or hovers the cursor over a certain element.
  • The user presses a key on the keyboard.
  • The user resizes or closes the browser window.
  • A web page finishes loading.
  • A form is submitted.
  • A video is played, paused, or ends.
  • An error occurs.

You can gather from this (and from glancing at theevent index) that there area lot of events that can be fired.

To react to an event, you attach anevent listener to it. This is a code feature that listens out for the event firing. When the event fires, anevent handler function (referenced by, or contained inside the event listener) is called to respond to the event firing. When such a block of code is set up to run in response to an event, we say we areregistering an event handler.

An example: handling a click event

In the following example, we have a single<button> in the page:

html
<button>Change color</button>
button {  margin: 10px;}

Then we have some JavaScript. We'll look at this in more detail in the next section, but for now we can just say: it adds an event listener to the button's"click" event, and the contained handler function reacts to the event by setting the page background to a random color:

js
const btn = document.querySelector("button");function random(number) {  return Math.floor(Math.random() * (number + 1));}btn.addEventListener("click", () => {  const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;  document.body.style.backgroundColor = rndCol;});

The example output is as follows. Try clicking the button:

Using addEventListener()

As we saw in the last example, objects that can fire events have anaddEventListener() method, and this is the recommended mechanism for adding event listeners.

Let's take a closer look at the code from the last example:

js
const btn = document.querySelector("button");function random(number) {  return Math.floor(Math.random() * (number + 1));}btn.addEventListener("click", () => {  const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;  document.body.style.backgroundColor = rndCol;});

The HTML<button> element will fire aclick event when the user clicks it. We call theaddEventListener() method on it to add an event listener; this takes two parameters:

  • the string"click", to indicate that we want to listen to theclick event. Buttons can fire lots of other events, such as"mouseover" when the user moves their mouse over the button, or"keydown" when the user presses a key and the button is focused.
  • a function to call when the event happens. In our case, the defined anonymous function generates a random RGB color and sets thebackground-color of the page<body> to that color.

You could also create a separate named function, and reference that in the second parameter ofaddEventListener(), like this:

js
const btn = document.querySelector("button");function random(number) {  return Math.floor(Math.random() * (number + 1));}function changeBackground() {  const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;  document.body.style.backgroundColor = rndCol;}btn.addEventListener("click", changeBackground);

Listening for other events

There are many different events that can be fired by a button element. Let's experiment.

First, make a local copy ofrandom-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 changingclick to the following different values in turn, and observing the results in the example:

  • focus andblur — The color changes when the button is focused and unfocused; try pressing the tab to focus on the button and press the tab again to focus away from the button.These are often used to display information about filling in form fields when they are focused, or to display an error message if a form field is filled with an incorrect value.
  • dblclick — The color changes only when the button is double-clicked.
  • mouseover andmouseout — The color changes when the mouse pointer hovers over the button, or when the pointer moves off the button, respectively.

Some events, such asclick, are available on nearly any element. Others are more specific and only useful in certain situations: for example, theplay event is only available on elements that have play functionality, such as<video>.

Removing listeners

If you've added an event listener usingaddEventListener(), you can remove it again if desired. The most common way to do this is by using theremoveEventListener() method. For example, the following line would remove theclick event handler we saw previously:

js
btn.removeEventListener("click", changeBackground);

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 event

By making more than one call toaddEventListener(), providing different handlers, you can have multiple handler functions running in response to a single event:

js
myElement.addEventListener("click", functionA);myElement.addEventListener("click", functionB);

Both functions would now run when the element is clicked.

Other event listener mechanisms

We recommend that you useaddEventListener() to register event handlers. It's the most powerful method and scales best with more complex programs. However, there are two other ways of registering event handlers that you might see:event handler properties andinline event handlers.

Event handler properties

Objects (such as buttons) that can fire events also usually have properties whose name ison followed by the name of an event. For example, elements have a propertyonclick.This is called anevent handler property. To listen for the event, you can assign the handler function to the property.

For example, we could rewrite the random color example like this:

js
const btn = document.querySelector("button");function random(number) {  return Math.floor(Math.random() * (number + 1));}btn.onclick = () => {  const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;  document.body.style.backgroundColor = rndCol;};

You can also set the handler property to a named function:

js
const btn = document.querySelector("button");function random(number) {  return Math.floor(Math.random() * (number + 1));}function bgChange() {  const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;  document.body.style.backgroundColor = rndCol;}btn.onclick = bgChange;

Event handler properties have disadvantages compared toaddEventListener(). One of the most significant is that you can'tadd more than one listener for a single event. The following pattern doesn't work, because any subsequent attempts to set the property value will overwrite earlier ones:

js
element.onclick = function1;element.onclick = function2;

Inline event handlers — don't use these

You might also see a pattern like this in your code:

html
<button>Press me</button>
js
function bgChange() {  const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;  document.body.style.backgroundColor = rndCol;}

The earliest method of registering event handlers found on the Web involvedevent handler HTML attributes (orinline event handlers) like the one shown above — the attribute value contains the JavaScript code you want to run when the event occurs.The above example invokes a function defined inside a<script> element on the same page, but you could also insert JavaScript directly inside the attribute, for example:

html
<button>  Press me</button>

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:

js
const buttons = document.querySelectorAll("button");for (const button of buttons) {  button.addEventListener("click", bgChange);}

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 asevent,evt, ore.This is called theevent object, and it is automatically passed to event handlers to provide extra features and information.For example, let's rewrite our random color example to include an event object:

js
const btn = document.querySelector("button");function random(number) {  return Math.floor(Math.random() * (number + 1));}function bgChange(e) {  const rndCol = `rgb(${random(255)} ${random(255)} ${random(255)})`;  e.target.style.backgroundColor = rndCol;  console.log(e);}btn.addEventListener("click", bgChange);

Note:You can find thefull source code for this example on GitHub (alsosee it running live).

Here you can see we are including an event object,e, in the function, and in the function setting a background color style one.target — which is the button itself.Thetarget property of the event object is always a reference to the element the event occurred upon.So, in this example, we are setting a random background color on the button, not the page.

Note:You can use any name you like for the event object — you just need to choose a name that you can reference inside the event handler function.e,evt, andevent are commonly used by developers because they are short and easy to remember.It's always good to be consistent — with yourself, and with others if possible.

Extra properties of event objects

Most event objects have a standard set of properties and methods available on the event object; see theEvent object reference for a full list.

Some event objects add extra properties that are relevant to that particular type of event. For example, thekeydown event fires when the user presses a key. Its event object is aKeyboardEvent, which is a specializedEvent object with akey property that tells you which key was pressed:

html
<input type="text" /><div></div>
js
const textBox = document.querySelector("#textBox");const output = document.querySelector("#output");textBox.addEventListener("keydown", (event) => {  output.textContent = `You pressed "${event.key}".`;});
div {  margin: 0.5rem 0;}

Try typing into the text box and see the output:

Preventing default behavior

Sometimes, 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 an example.

First, a simple HTML form that requires you to enter your first and last name:

html
<form action="#">  <div>    <label for="fname">First name: </label>    <input type="text" />  </div>  <div>    <label for="lname">Last name: </label>    <input type="text" />  </div>  <div>    <input type="submit" />  </div></form><p></p>
div {  margin-bottom: 10px;}

Now some JavaScript — here we implement a basic check inside a handler for thesubmit event (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty.If they are, we call thepreventDefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:

js
const form = document.querySelector("form");const fname = document.getElementById("fname");const lname = document.getElementById("lname");const para = document.querySelector("p");form.addEventListener("submit", (e) => {  if (fname.value === "" || lname.value === "") {    e.preventDefault();    para.textContent = "You need to fill in both names!";  }});

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.

You can see the full examplerunning live — try it out there. For the full source code, seepreventdefault-validation.html.

It's not just web pages

Events 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.TheNode.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 likeon() to register an event listener, andonce() to register an event listener that unregisters after it has run once.The Node.jsHTTP connect event docs provide a good example.

You can also use JavaScript to build cross-browser add-ons — browser functionality enhancements — using a technology calledWebExtensions.The event model is similar to the web events model, but a bit different — event listener properties are written incamel case (such asonMessage rather thanonmessage), and need to be combined with theaddListener function.See theruntime.onMessage page for an example.

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.

Summary

In this chapter we've learned what events are, how to listen for events, and how to respond to them.

You've seen by now that elements in a web page can be nested inside other elements. For example, in thePreventing default behavior example, we have some text boxes, placed inside<div> elements, which in turn are placed inside a<form> element. What happens when a click event listener is attached to the<form> element, and the user clicks inside one of the text boxes? The associated event handler function is still fired via a process calledevent bubbling, which is covered in the next lesson.

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp