-
Notifications
You must be signed in to change notification settings - Fork 22.4k
/
index.md
65 lines (48 loc) · 2.3 KB
/
index.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
---
title: "Event: cancelable property"
short-title: cancelable
slug: Web/API/Event/cancelable
page-type: web-api-instance-property
browser-compat: api.Event.cancelable
---
{{APIRef("DOM")}}{{AvailableInWorkers}}
The **`cancelable`** read-only property of the {{domxref("Event")}} interface indicates whether the event
can be canceled, and therefore prevented as if the event never happened.
If the event is _not_ cancelable, then its `cancelable` property will be
`false` and the event listener cannot stop the event from occurring.
Most browser-native events that can be canceled are the ones that result from the user
interacting with the page. Canceling the {{domxref("Element/click_event", "click")}},
{{domxref("Element/wheel_event", "wheel")}}, or
{{domxref("Window/beforeunload_event", "beforeunload")}} events would prevent the user
from clicking on something, scrolling the page with the mouse wheel, or
navigating away from the page, respectively.
[Synthetic events](/en-US/docs/Web/API/Event/Event) created by other JavaScript
code define if they can be canceled when they are created.
To cancel an event, call the {{domxref("event.preventDefault", "preventDefault()")}}
method on the event. This keeps the implementation from executing the default action
that is associated with the event.
Event listeners that handle multiple kinds of events may want to check
`cancelable` before invoking their {{domxref("event.preventDefault", "preventDefault()")}} methods.
## Value
A boolean value, which is `true` if the event can be
canceled.
## Example
For example, browser vendors are proposing that the {{domxref("Element/wheel_event", "wheel")}} event can only be canceled [the first time the listener is called](https://github.com/WICG/interventions/issues/33) — any following `wheel` events cannot be canceled.
```js
function preventScrollWheel(event) {
if (typeof event.cancelable !== "boolean" || event.cancelable) {
// The event can be canceled, so we do so.
event.preventDefault();
} else {
// The event cannot be canceled, so it is not safe
// to call preventDefault() on it.
console.warn(`The following event couldn't be canceled:`);
console.dir(event);
}
}
document.addEventListener("wheel", preventScrollWheel);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}