DocumentFragment: append() method - Web APIs

DocumentFragment: append() method
=================================

 The **`DocumentFragment.append()`** method
 inserts a set of `Node` objects or string objects after
 the last child of the document fragment. String objects
 are inserted as equivalent `Text` nodes.

This method appends a child to a `DocumentFragment`. To append to an arbitrary element in the tree, see `Element.append()`.

Syntax
------

```js
append(param1)
append(param1, param2)
append(param1, param2, /\* …, \*/ paramN)
```

### Parameters

`param1`, …, `paramN`

A set of `Node` or string objects to insert.

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples
--------

### Appending an element to a document fragment

```js
let fragment = new DocumentFragment();
let div = document.createElement("div");
fragment.append(div);

fragment.children; // HTMLCollection [<div>]
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-parentnode-append① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `DocumentFragment.prepend()`
* `Element.append()`


DocumentFragment: replaceChildren() method - Web APIs

DocumentFragment: replaceChildren() method
==========================================

 The **`DocumentFragment.replaceChildren()`** method replaces the
 existing children of a `DocumentFragment` with a specified new set of children. These
 can be string or `Node` objects.

Syntax
------

```js
replaceChildren(param1)
replaceChildren(param1, param2)
replaceChildren(param1, param2, /\* …, \*/ paramN)
```

### Parameters

`param1`, …, `paramN`

 A set of `Node` or string objects to replace the
 `DocumentFragment`'s existing children with. If no replacement objects are
 specified, then the `DocumentFragment` is emptied of all child nodes.

### Return value

None (`undefined`).

### Exceptions

`HierarchyRequestError` `DOMException`

Thrown when the constraints of the node tree are violated.

Examples
--------

### Emptying a document fragment

`replaceChildren()` provides a very convenient mechanism for emptying a document fragment
 of all its children. You call it on the document fragment without any argument specified:

```js
let fragment = new DocumentFragment();
let div = document.createElement("div");
let p = document.createElement("p");
fragment.append(p);
fragment.prepend(div);

fragment.children; // HTMLCollection [<div>, <p>]

fragment.replaceChildren();

fragment.children; // HTMLCollection []
```

Specifications
--------------

| Specification |
| --- |
| DOM Standard # ref-for-dom-parentnode-replacechildren① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `DocumentFragment.prepend()`
* `DocumentFragment.append()`


GPUSampler: label property - Web APIs

GPUSampler: label property
==========================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

 The **`label`** property of the
 `GPUSampler` interface provides a label that can be used to identify the object, for example in `GPUError` messages or console warnings.

This can be set by providing a `label` property in the descriptor object passed into the originating `GPUDevice.createSampler()` call, or you can get and set it directly on the `GPUSampler` object.

Value
-----

A string. If this has not been previously set as described above, it will be an empty string.

Examples
--------

Setting and getting a label via `GPUSampler.label`:

```js
// ...

const sampler = device.createSampler({
  compare: "less",
});

sampler.label = "mysampler";

console.log(sampler.label); // "mysampler"
```

Setting a label via the originating `GPUDevice.createSampler()` call, and then getting it via `GPUSampler.label`:

```js
// ...

const sampler = device.createSampler({
  compare: "less",
  label: "mysampler",
});

console.log(sampler.label); // "mysampler"
```

Specifications
--------------

| Specification |
| --- |
| WebGPU # dom-gpuobjectbase-label |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The WebGPU API


PaymentRequest: paymentmethodchange event - Web APIs

PaymentRequest: paymentmethodchange event
=========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The **`paymentmethodchange`** event is delivered the Payment Request API to a `PaymentRequest` object when the user changes the payment method within a given payment handler.

For example, if the user switches from one credit card to another on their Apple Pay account, a `paymentmethodchange` event is fired to let you know about the change.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("paymentmethodchange", (event) => {});

onpaymentmethodchange = (event) => {};
```

Event type
----------

A `PaymentMethodChangeEvent`. Inherits from `Event`.

Event

PaymentRequestUpdateEvent

PaymentMethodChangeEventEvent properties
----------------

*In addition to the properties below, this interface includes properties inherited from `PaymentRequestUpdateEvent`.*

`methodDetails` Read only

An object containing payment method-specific data useful when handling a payment method change. If no such information is available, this value is `null`.

`methodName` Read only

A string containing the payment method identifier, a string which uniquely identifies a particular payment method. This identifier is usually a URL used during the payment process, but may be a standardized non-URL string as well, such as `basic-card`. The default value is the empty string, `""`.

Examples
--------

Let's take a look at an example. This code creates a new `PaymentRequest`, adds a handler for the `paymentmethodchange` event by calling the request's `addEventListener()`, then calls `show()` to present the payment interface to the user.

The code assumes the existence of a method `detailsForTransaction()`, which will return an object that can be passed as the `details` argument to the `PaymentRequest` constructor.

```js
const paymentRequest = new PaymentRequest(
  paymentMethods,
  detailsForTransaction(),
);

paymentRequest.addEventListener(
  "paymentmethodchange",
  handlePaymentChange,
  false,
);

paymentRequest
  .show()
  .then((response) => response.complete("success"))
  .catch((err) => console.error(`Error handling payment request: ${err}`));
```

The event handler function itself, `handlePaymentChange()`, looks like this:

```js
handlePaymentChange = (event) => {
  const detailsUpdate = {};

  if (event.methodName === "https://apple.com/apple-pay") {
    const serviceFeeInfo = calculateServiceFee(event.methodDetails);
    Object.assign(detailsUpdate, serviceFeeInfo);
  }

  event.updateWith(detailsUpdate);
};
```

This begins by looking at the event's `methodName` property; if that indicates that the user is trying to use Apple Pay, we pass the `methodDetails` into a function called `calculateServiceFee()`, which we might create to take the information about the transaction, such as the underlying credit card being used to service the Apple Pay request, and compute and return an object that specifies changes to be applied to the `PaymentRequest` in order to add any service fees that the payment method might require.

Before the event handler returns, it calls the event's `updateWith()` method to integrate the changes into the request.

Specifications
--------------

| Specification |
| --- |
| Payment Request API 1.1 # dfn-paymentmethodchange |
| Payment Request API 1.1 # onpaymentmethodchange-attribute |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Payment Request API
* Using the Payment Request API
* `merchantvalidation` event
* `shippingaddresschange` event
* `shippingoptionchange` event


PaymentRequest: shippingoptionchange event - Web APIs

PaymentRequest: shippingoptionchange event
==========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

For payment requests that request shipping information, and for which shipping options are offered, the **`shippingoptionchange`** event is sent to the `PaymentRequest` whenever the user chooses a shipping option from the list of available options.

The string identifying the currently-selected shipping option can be found in the `shippingOption` property.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("shippingoptionchange", (event) => {});

onshippingoptionchange = (event) => {};
```

Event type
----------

A `PaymentRequestUpdateEvent`. Inherits from `Event`.

Event

PaymentRequestUpdateEventEvent properties
----------------

*Provides only the properties inherited from `Event`.*

Examples
--------

This code snippet sets up a handler for the `shippingoptionchange` event. The code recalculates the total charge for the payment based on the selected shipping option. For example, if there are three options (such as "Free ground shipping", "2-day air", and "Next day"), each time the user chooses one of those options, this event handler is called to recalculate the total based on the changed shipping option.

```js
paymentRequest.addEventListener(
  "shippingoptionchange",
  (event) => {
    const value = calculateNewTotal(paymentRequest.shippingOption);
    const total = {
      currency: "EUR",
      label: "Total due",
      value,
    };
    event.updateWith({ total });
  },
  false,
);
```

After calling a custom function, `calculateNewTotal()`, to compute the updated total based on the newly-selected shipping option as specified by the `shippingOption`. The revised total is submitted back to the payment request by calling the event's `updateWith()` method.

You can also create an event handler for `shippingoptionchange` using its corresponding event handler property, `onshippingoptionchange`:

```js
paymentRequest.onshippingoptionchange = (event) => {
  const value = calculateNewTotal(paymentRequest.shippingOption);
  const total = {
    currency: "EUR",
    label: "Total due",
    value,
  };
  event.updateWith({ total });
};
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PaymentRequest: shippingOption property - Web APIs

PaymentRequest: shippingOption property
=======================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`shippingOption`** read-only attribute of
 the `PaymentRequest` interface returns either the id of a selected shipping
 option, null (if no shipping option was set to be selected) or a shipping option
 selected by the user. It is initially `null` by when no "selected" shipping
 options are provided.

 This attribute is only populated if the constructor is called with the
 `requestShipping` flag set to `true`. If
 `requestShipping` was `false` (or missing),
 `shippingOption` returns `null`, even the developer provides
 a selected a shipping option.

Value
-----

Examples
--------

 In the example below, the `shippingaddresschange` and
 the `shippingoptionchange` events are dispatched. In
 each calls to `updateDetails()` are made, one using a promise, and the other
 with a plain JS object. This demonstrates synchronous and asynchronous updates to a
 payment sheet.

```js
const request = new PaymentRequest(methodData, details, options);
// Async update to details
request.onshippingaddresschange = (ev) => {
  ev.updateWith(checkShipping(request));
};
// Sync update to the total
request.onshippingoptionchange = (ev) => {
  const shippingOption = shippingOptions.find(
    (option) => option.id === request.id,
  );
  const newTotal = {
    currency: "USD",
    label: "Total due",
    value: calculateNewTotal(shippingOption),
  };
  ev.updateWith({ ...details, total: newTotal });
};
async function checkShipping(request) {
  try {
    const json = request.shippingAddress.toJSON();

    await ensureCanShipTo(json);
    const { shippingOptions, total } = await calculateShipping(json);

    return { ...details, shippingOptions, total };
  } catch (err) {
    return { ...details, error: `Sorry! we can't ship to your address.` };
  }
}
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PaymentRequest: shippingAddress property - Web APIs

PaymentRequest: shippingAddress property
========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`shippingAddress`** read-only property of
 the `PaymentRequest` interface returns the shipping address provided by the
 user. It is `null` by default.

Value
-----

Examples
--------

 Generally, the user agent will fill the `shippingAddress` property value.
 You can trigger this by setting
 `PaymentOptions.requestShipping` to `true` when calling
 the `PaymentRequest` constructor.

 In the example below, the cost of shipping varies by geography. When the
 `shippingaddresschange` is
 called, `updateDetails()` is called to update the details of
 the `PaymentRequest`, using `shippingAddress` to set the correct
 shipping cost.

```js
// Initialization of PaymentRequest arguments are excerpted for the sake of
// brevity.
const payment = new PaymentRequest(supportedInstruments, details, options);

payment.addEventListener("shippingaddresschange", (evt) => {
  evt.updateWith(
    new Promise((resolve) => {
      updateDetails(details, request.shippingAddress, resolve);
    }),
  );
});

payment
  .show()
  .then((paymentResponse) => {
    // Processing of paymentResponse excerpted for brevity.
  })
  .catch((err) => {
    console.error("Uh oh, something bad happened", err.message);
  });

function updateDetails(details, shippingAddress, resolve) {
  if (shippingAddress.country === "US") {
    const shippingOption = {
      id: "",
      label: "",
      amount: { currency: "USD", value: "0.00" },
      selected: true,
    };
    if (shippingAddress.region === "MO") {
      shippingOption.id = "mo";
      shippingOption.label = "Free shipping in Missouri";
      details.total.amount.value = "55.00";
    } else {
      shippingOption.id = "us";
      shippingOption.label = "Standard shipping in US";
      shippingOption.amount.value = "5.00";
      details.total.amount.value = "60.00";
    }
    details.displayItems.splice(2, 1, shippingOption);
    details.shippingOptions = [shippingOption];
  } else {
    delete details.shippingOptions;
  }
  resolve(details);
}
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PaymentRequest: PaymentRequest() constructor - Web APIs

PaymentRequest: PaymentRequest() constructor
============================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`PaymentRequest()`** constructor
 creates a new `PaymentRequest` object which will be used to handle the
 process of generating, validating, and submitting a payment request.

Syntax
------

```js
new PaymentRequest(methodData, details)
new PaymentRequest(methodData, details, options)
```

### Parameters

`methodData`

 Contains an array of identifiers for the payment methods the merchant website
 accepts and any associated payment method specific data. Each item in the array
 contains the following fields:

`supportedMethods`

A string containing a payment method identifier. This is either a URL or one of the standardized payment method identifiers. The value and structure of the `data` field will vary depending on the value of the `supportedMethods` field.

`data`

 A JSON-serializable object that provides optional information that might be
 needed by the supported payment methods. This has to conform to the type expected
 by the payment handler indicated by `supportedMethods`. Developers need to consult
 whomever controls the payment methods for the expected shape of the data object. If `supportedMethods` is `secure-payment-confirmation`, then `data` needs to conform to the `SecurePaymentConfirmationRequest` dictionary.

`details`

 Provides information about the requested transaction. This parameter contains the
 following fields:

`total`

The total amount of the payment request.

`id` Optional

 A free-form identifier for this payment request. If a value is not supplied, the
 browser will construct one.

`displayItems`

 An array of optional line items for the payment request that the user agent may
 display, such as product details, tax, and shipping.

`shippingOptions`

 The shipping options the user may choose from. If this sequence is blank, it
 indicates the merchant cannot ship to the current shipping address. The default
 shipping option may be indicated in this sequence.

`modifiers`

 Modifiers for specific payment methods; for example, adjusting the total amount
 based on the payment method. This parameter contains the following fields:

`additionalDisplayItems`

 An array of items to be appended to the `details.displayItems`
 property. This property is commonly used to add a discount or surcharge line
 item indicating the different amount in `details.modifiers.total`.

`data`

 A JSON-serializable object that provides optional information that might be
 needed by the supported payment methods.

`total`

 A total amount for the payment request that overrides value in
 details.total. This is typically used when
 `details.modifiers.additionalItems` adds a discount or a purchase
 to the request.

`options` Optional

 Lets you set options that control the behavior of the user agent. This parameter
 contains the following fields:

`requestPayerName`

 A Boolean indicating whether the user agent should collect the payer's name and
 submit it with the payment request. The default is `false`.

`requestPayerEmail`

 A Boolean indicating whether the user agent should collect the payer's email
 address and submit it with the payment request. The default is `false`.

`requestPayerPhone`

 A Boolean indicating whether the user agent should collect the payer's phone
 number and submit it with the payment request. The default is `false`.

`requestShipping`

 A Boolean indicating whether the user agent should collect the payer's shipping
 address and submit it with the payment request. If you set this type to true, you
 should select an appropriate `shippingType`. The default is
 `false`.

`shippingType`

 Lets you specify how the user interface refers to shipping when the word
 'shipping' isn't appropriate for your use case. For example, in English speaking
 countries you would say "pizza delivery" not "pizza shipping". Valid values are
 `"shipping"`, `"delivery"`, and `"pickup"`.
 Quotation marks must be included. The default value is `"shipping"`.

### Return value

 A new `PaymentRequest` object, configured for use as configured by the
 input parameters.

### Exceptions

`SecurityError` `DOMException`

Use of this feature was blocked by a Permissions Policy.

Examples
--------

 The following example shows minimal functionality and focuses instead on showing the
 complete context of instantiating a `PaymentRequest` object.

```js
const supportedInstruments = [
  {
    supportedMethods: "https://example.com/pay",
  },
];

const details = {
  total: { label: "Donation", amount: { currency: "USD", value: "65.00" } },
  displayItems: [
    {
      label: "Original donation amount",
      amount: { currency: "USD", value: "65.00" },
    },
  ],
  shippingOptions: [
    {
      id: "standard",
      label: "Standard shipping",
      amount: { currency: "USD", value: "0.00" },
      selected: true,
    },
  ],
};

const options = { requestShipping: true };

try {
  const request = new PaymentRequest(supportedInstruments, details, options);
  // Add event listeners here.
  // Call show() to trigger the browser's payment flow.
  request
    .show()
    .then((instrumentResponse) => {
      // Do something with the response from the UI.
    })
    .catch((err) => {
      // Do something with the error from request.show().
    });
} catch (e) {
  // Catch any other errors.
}
```

Specifications
--------------

| Specification |
| --- |
| Payment Request API 1.1 # constructor |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PaymentRequest: merchantvalidation event - Web APIs

PaymentRequest: merchantvalidation event
========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**`merchantvalidation`** events are delivered by the Payment Request API to a `PaymentRequest` object when a payment handler requires that the merchant requesting the purchase validate itself as permitted to use the payment handler.

Learn how the merchant validation process works.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("merchantvalidation", (event) => {});

onmerchantvalidation = (event) => {};
```

Event type
----------

A `MerchantValidationEvent`. Inherits from `Event`.

Event properties
----------------

`MerchantValidationEvent.methodName`

A string providing a unique payment method identifier for the payment handler that's requiring validation. This may be either one of the standard payment method identifier strings or a URL that both identifies and handles requests for the payment handler, such as `https://apple.com/apple-pay`.

`MerchantValidationEvent.validationURL`

A string specifying a URL from which the site or app can fetch payment handler specific validation information. Once this data is retrieved, the data (or a promise resolving to the validation data) should be passed into `complete()` to validate that the payment request is coming from an authorized merchant.

Examples
--------

In this example, an event handler is established for the `merchantvalidation` event. It uses the `fetch()` to send a request to its own server with an argument of the payment method's validation URL, obtained from the event's `validationURL` property. The merchant server should access the validation URL in accordance with the payment method documentation. Typically, a client should not access the validation URL.

```js
request.addEventListener("merchantvalidation", (event) => {
  event.complete(async () => {
    const merchantServerUrl = `${
 window.location.origin
 }/validate?url=${encodeURIComponent(event.validationURL)}`;
    // get validation data, and complete validation;
    return await fetch(merchantServerUrl).then((response) => response.text());
  }, false);
});

const response = await request.show();
```

How merchant server handles the validation depends on the server implementation and payment method documentation. The content delivered by the validation server is forwarded to the merchant server and is then returned from the `fetch()` call's fulfillment handler to the `complete()` method on the event. This response lets the payment handler know if the merchant is validated.

You can also use the `onmerchantvalidation` event handler property to set up the handler for this event:

```js
request.onmerchantvalidation = (event) => {
  event.complete(async () => {
    const merchantServerUrl = `${
 window.location.origin
 }/validate?url=${encodeURIComponent(event.validationURL)}`;
    // get validation data, and complete validation;
    return await fetch(merchantServerUrl).then((response) => response.text());
  });
};

const response = await request.show();
```

For more information, see Merchant validation.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Payment Request API
* Using the Payment Request API
* `onmerchantvalidation` event handler property
* Merchant validation
* `paymentmethodchange` event
* `shippingaddresschange` event
* `shippingoptionchange` event


PaymentRequest: shippingType property - Web APIs

PaymentRequest: shippingType property
=====================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`shippingType`** read-only property of the
 `PaymentRequest` interface returns one of `"shipping"`,
 `"delivery"`, `"pickup"`, or `null` if one was not
 provided by the constructor.

Value
-----

 One of `"shipping"`, `"delivery"`, `"pickup"`, or
 `null`.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PaymentRequest: show() method - Web APIs

PaymentRequest: show() method
=============================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`PaymentRequest`** interface's
 **`show()`** method instructs the user agent to begin the
 process of showing and handling the user interface for the payment request to the
 user.

 Only one payment request can be in the process of being handled at once, across all
 documents. Once one `PaymentRequest`'s `show()` method has been
 called, any other call to `show()` will by rejected with an
 `AbortError` until the returned promise has been concluded, either by being
 fulfilled with a `PaymentResponse` indicating the results of the payment
 request, or by being rejected with an error.

**Note:** In reality, despite the fact that the specification says this
 can't be done, some browsers, including Firefox, support multiple active payment
 requests at a time.

 If your architecture doesn't necessarily have all of the data ready to go at the moment
 it instantiates the payment interface by calling `show()`, specify the
 `detailsPromise` parameter, providing a `Promise` that is
 fulfilled once the data is ready. If this is provided, `show()` will not
 allow the user to interact with the payment interface until the promise is fulfilled, so
 that data can be updated prior to the user engaging with the payment process.

 Processing the result and, if necessary, calling `PaymentResponse.retry()`
 to retry a failed payment can all be done either asynchronously or synchronously,
 depending on your needs. For the best user experience, asynchronous solutions are
 typically the best way to go. Most examples on MDN and elsewhere use
 `async`/`await`
 to wait asynchronously while results are validated and so forth.

Syntax
------

```js
show()
show(detailsPromise)
```

### Parameters

`detailsPromise` Optional

 An optional `Promise` that you can provide if your architecture requires
 that the payment request's details need to be updated between instantiating the
 payment interface and the user beginning to interact with it. The promise should
 resolve with an object containing the updated information:

`displayItems` Optional

An array of objects, each describing one line item for the payment request. These represent the line items on a receipt or invoice, each with the following properties:

`amount`

An object describing the monetary value of the item. This object includes the following fields:

`currency`

A string containing a valid 3-letter ISO 4217 currency identifier (ISO 4217) indicating the currency used for the payment `value`.

`value`

A string containing a valid decimal value representing the mount of currency constituting the payment amount. This string must only contain an optional leading "-" to indicate a negative value, then one or more digits from 0 to 9, and an optional decimal point (".", regardless of locale) followed by at least one more digit. No whitespace is permitted.

`label`

A string specifying a human-readable name or description of the item or service being charged for. This may be displayed to the user by the user agent, depending on the design of the interface.

`pending`

A Boolean value which is `true` if the specified `amount` has not yet been finalized. This can be used to show items such as shipping or tax amounts that depend upon the selection of shipping address, shipping option, or so forth. The user agent may show this information but is not required to do so.

`error` Optional
Deprecated

Non-standard

A string specifying an error message to present to the user\*.\* When calling `updateWith()`, including `error` in the updated data causes the user agent to display the text as a general error message. For address-field specific errors, use the `shippingAddressErrors` field.

`modifiers` Optional

An array of objects, each describing a modifier for particular payment method identifiers, each with the following properties:

`supportedMethods`

A string that represents the payment method identifier. The payment method identifier only applies if the user selects this payment method.

`total` Optional

An object that overrides the `total` property of the `detailsPromise` parameter if this payment method is selected by the user. The property takes the same input with the `total` property of the `detailsPromise` parameter.

`additionalDisplayItems` Optional

An `Array` of objects provide additional display items that are appended to the `displayItems` property of the `detailsPromise` parameter if this payment method is selected by the user. This property is commonly used to add a discount or surcharge line item indicating the reason for the different total amount for the selected payment method that the user agent may display. The property takes the same input with the `displayItems` property of the `detailsPromise` parameter.

`data` Optional

A serializable object that provides optional information that might be needed by the supported payment methods.

For example, you can use one to adjust the total payment amount based on the selected payment method ("5% cash discount!").

`shippingAddressErrors` Optional
Deprecated

Non-standard

An object which includes an error message for each property of the shipping address that could not be validated.

`shippingOptions` Optional
Deprecated

Non-standard

An array of objects, each describing one available shipping option from which the user may choose.

`total` Optional

An object with the same properties as the objects in `displayItems` providing an updated total for the payment. Make sure this equals the sum of all of the items in `displayItems`. *This is not calculated automatically*. You must update this value yourself anytime the total amount due changes. This lets you have flexibility for how to handle things like tax, discounts, and other adjustments to the total price charged.

### Return value

 A `Promise` that eventually resolves with a `PaymentResponse`.
 The promise is resolved when the user accepts the payment request (such as by clicking a
 "Pay" button in the browser's payment sheet).

### Exceptions

Exceptions are not thrown but returned when the `Promise` rejects.

`AbortError` `DOMException`

 Returned if the
 user agent is already showing a payment panel. Only one payment
 panel may be visible at a time *across all documents loaded by the user
agent*.

 The promise is also rejected with `AbortError` if the user cancels the
 payment request.

`InvalidStateError` `DOMException`

 Returned if the same payment has
 already been shown for this request (its state is `interactive` because it
 is being shown already).

`NotSupportedError` `DOMException`

 Returned if the user agent does not
 support the payment methods specified when the
 `PaymentRequest` constructor was called.

`SecurityError` `DOMException`

 Returned if the call to
 `show()` was not in response to a user action, such as a `click`
 or `keyup` event. Other reasons a `SecurityError` may be thrown
 are at the discretion of the user agent, and may include situations such as too many
 calls to `show()` being made in a short time or `show()` being
 called while payment requests are blocked by parental controls.

Security
--------

Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.

Usage notes
-----------

 The most common patterns for using `show()` involve either the
 `async`/`await`
 syntax or the use of `show().then().catch()` to handle the response and any
 possible rejection. Those look like this:

### async/await syntax

 Using `await` to wait for a promise to be resolved makes it possible to
 write the code to handle payments particularly cleanly:

```js
async function processPayment() {
  try {
    const payRequest = new PaymentRequest(methodData, details, options);

    payRequest.onshippingaddresschange = (ev) =>
      ev.updateWith(checkAddress(payRequest));
    payRequest.onshippingoptionchange = (ev) =>
      ev.updateWith(checkShipping(payRequest));

    const response = await payRequest.show();
    await validateResponse(response);
  } catch (err) {
    /\* handle the error; AbortError usually means a user cancellation \*/
  }
}
```

 In this code, the methods `checkAddress()` and `checkShipping()`,
 respectively, check the shipping address and the shipping option changes and supply in
 response either an object or a promise to return one;
 this object contains the fields in the `PaymentResponse` which have been or
 need to be changed.

 The `validateResponse()` method, below, is called once `show()`
 returns, in order to look at the returned `response` and either submit the
 payment or reject the payment as failed:

```js
async function validateResponse(response) {
  try {
    if (await checkAllValues(response)) {
      await response.complete("success");
    } else {
      await response.complete("fail");
    }
  } catch (err) {
    await response.complete("fail");
  }
}
```

 Here, a custom function called `checkAllValues()` looks at each value in the
 `response` and ensures that they're valid, returning `true` if
 every field is valid or `false` if any are not. If and only if every field is
 valid, the `complete()` method is called on the
 response with the string `"success"`, which indicates that everything is
 valid and that the payment can complete accordingly.

 If any fields have unacceptable values, or if an exception is thrown by the previous
 code, `complete()` is called with the string `"fail"`, which
 indicates that the payment process is complete and failed.

 Instead of immediately failing, you could choose to call
 `retry()` on the response object to ask the user
 agent to try to process the payment again; this should usually only be done after the
 user has made any needed corrections to the order.

 Starting the payment process, in the end, is as simple as calling the
 `processPayment()` method.

### then/catch syntax

 You can also use the older promise-based approach to work with payments, using the
 `then()` and `catch()`
 functions on the promise returned by `show()`:

```js
function processPayment() {
  const payRequest = new PaymentRequest(methodData, details, options);

  payRequest.onshippingaddresschange = (ev) =>
    ev.updateWith(checkAddress(payRequest));
  payRequest.onshippingoptionchange = (ev) =>
    ev.updateWith(checkShipping(payRequest));

  payRequest
    .show()
    .then((response) => validateResponse(response))
    .catch((err) => handleError(err));
}
```

 This is functionally equivalent to the `processPayment()` method using the
 `await` syntax.

```js
function validateResponse(response) {
  checkAllValues(response)
    .then((response) => response.complete("success"))
    .catch((response) => response.complete("fail"));
}
```

 You could even have `checkAllValues()` be a synchronous function, although
 that may have performance implications you don't want to deal with:

```js
function validateResponse(response) {
  if (checkAllValues(response)) {
    response.complete("success");
  } else {
    response.complete("fail");
  }
}
```

 See the article Using promises for more information if you need more information about working with
 promises.

Examples
--------

 In the following example, a `PaymentRequest` object is instantiated before
 the `show()` method is called. This method triggers the user agent's built-in
 process for retrieving payment information from the user. The `show()` method
 returns a `Promise` that resolves to a `PaymentResponse` object
 when the user interaction is complete. The developer then uses the information in
 the `PaymentResponse` object to format and send payment data to the server.
 You should send the payment information to the server asynchronously so that the final
 call to `paymentResponse.complete()` can indicate the success or failure of
 the payment.

```js
button.onclick = async function handlePurchase() {
  // Initialization of PaymentRequest arguments are excerpted for the sake of
  // brevity.
  const payment = new PaymentRequest(methods, details, options);
  try {
    const response = await payment.show();
    // Process response here, including sending payment instrument
    // (e.g., credit card) information to the server.
    // paymentResponse.methodName contains the selected payment method
    // paymentResponse.details contains a payment method specific response
    await response.complete("success");
  } catch (err) {
    console.error("Uh oh, something bad happened", err.message);
  }
};
```

 The following example shows how to update the payment sheet as it's being presented to
 the end-user.

```js
async function requestPayment() {
  // We start with AU$0 as the total.
  const initialDetails = {
    total: {
      label: "Total",
      amount: { value: "0", currency: "AUD" },
    },
  };
  const request = new PaymentRequest(methods, initialDetails, options);
  // Check if the user supports the `methods`
  if (!(await request.canMakePayment())) {
    return; // no, so use a web form instead.
  }
  // Let's update the total as the sheet is shown
  const updatedDetails = {
    total: {
      label: "Total",
      amount: { value: "20", currency: "AUD" },
    },
  };
  const response = await request.show(updatedDetails);
  // Check response, etc.
}

document.getElementById("buyButton").onclick = requestPayment;
```

Specifications
--------------

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentrequest-show |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Payment Request API
* Using the Payment Request API
* `PaymentRequest.abort()`
* `PaymentResponse`
* `PaymentResponse.retry()`
* `PaymentResponse.complete()`


PaymentRequest: canMakePayment() method - Web APIs

PaymentRequest: canMakePayment() method
=======================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The `PaymentRequest` method
 **`canMakePayment()`** determines whether or not the request
 is configured in a way that is compatible with at least one payment method supported
 by the user agent.

 You can call this before calling
 `show()` to provide a streamlined user experience
 when the user's browser can't handle any of the payment methods you accept.

 For instance, you might call `canMakePayment()` to determine if the browser
 will let the user pay using Payment Request API, and if it won't, you could fall back to
 another payment method, or offer a list of methods that aren't handled by Payment
 Request API (or even provide instructions for paying by mail or by phone).

Syntax
------

```js
canMakePayment()
```

### Parameters

None.

### Return value

 A `Promise` to a boolean value that resolves to `true`
 if the user agent supports any of the payment methods supplied when instantiating the
 request using the `PaymentRequest`
 constructor. If the payment can't be processed, the promise receives a value of
 `false`.

**Note:** If you call this too often, the browser may reject the
 returned promise with a `DOMException`.

Examples
--------

 In the following example, is excerpted from a demo that asynchronously builds a `PaymentRequest` object for
 both Apple Pay and Example Pay. It wraps the call to `canMakePayment()` in
 feature detection, and calls an appropriate callback depending on the resolution of the
 `Promise`.

```js
async function initPaymentRequest() {
  const details = {
    total: {
      label: "Total",
      amount: {
        currency: "USD",
        value: "0.00",
      },
    },
  };

  const supportsApplePay = new PaymentRequest(
    [{ supportedMethods: "https://apple.com/apple-pay" }],
    details,
  ).canMakePayment();

  // Supports Apple Pay?
  if (await supportsApplePay) {
    // show Apple Pay logo, for instance
    return;
  }

  // Otherwise, let's see if we can use Example Pay
  const supportsExamplePay = await new PaymentRequest(
    [{ supportedMethods: "https://example.com/pay" }],
    details,
  ).canMakePayment();

  if (supportsExamplePay) {
    // show Example Pay support
    return;
  }

  // Otherwise, make payments using HTML form element
}
```

Specifications
--------------

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentrequest-canmakepayment |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `PaymentRequest.show()`


PaymentRequest: abort() method - Web APIs

PaymentRequest: abort() method
==============================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The `PaymentRequest.abort()` method of the `PaymentRequest`
 interface causes the user agent to end the payment request and to remove any user
 interface that might be shown.

Syntax
------

```js
abort()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

 The following example sets up a timeout to clear the payment request that might have
 been abandoned or neglected.

```js
const request = new PaymentRequest(supportedInstruments, details, options);

const paymentTimeout = setTimeout(
  () => {
    clearTimeout(paymentTimeout);
    request
      .abort()
      .then(() => {
        print("Payment timed out after 20 minutes.");
      })
      .catch(() => {
        print(
          "Unable to abort, because the user is currently in the process " +
            "of paying.",
        );
      });
  },
  20 \* 60 \* 1000,
); /\* 20 minutes \*/
```

Specifications
--------------

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentrequest-abort |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `PaymentRequest.abort()`


PaymentRequest: id property - Web APIs

PaymentRequest: id property
===========================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

 The **`id`** read-only attribute of the
 `PaymentRequest` interface returns a unique identifier for a particular
 `PaymentRequest` instance.

 When constructing an instance of the `PaymentRequest`, you are able to
 supply an custom id. If none is provided, the browser automatically sets the id value to a UUID.

Example
-------

This example shows how to give a `PaymentRequest` instance a custom id.

```js
const details = {
  id: "super-store-order-123-12312",
  total: {
    label: "Total due",
    amount: { currency: "USD", value: "65.00" },
  },
};
const request = new PaymentRequest(methodData, details);
console.log(request.id); // super-store-order-123-12312
```

 The `id` is then also available in the `PaymentResponse`
 returned from the `show()` method, but under the `requestId`
 attribute.

```js
const response = await request.show();
console.log(response.requestId === request.id);

// And in serialized form too
const json = response.toJSON();
console.log(json.requestId, response.requestId, request.id);
```

Value
-----

A string.

Specifications
--------------

| Specification |
| --- |
| Payment Request API 1.1 # dom-paymentrequest-id |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


PaymentRequest: shippingaddresschange event - Web APIs

PaymentRequest: shippingaddresschange event
===========================================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`shippingaddresschange`** event is sent to the `PaymentRequest` object when the user selects a shipping address or changes details of their shipping address.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("shippingaddresschange", (event) => {});

onshippingaddresschange = (event) => {};
```

Event type
----------

A `PaymentRequestUpdateEvent`. Inherits from `Event`.

Event

PaymentRequestUpdateEventEvent properties
----------------

*Provides only the properties inherited from `Event`.*

Usage notes
-----------

Depending on the browser, the shipping address information may be redacted for privacy reasons. That is, the `PaymentAddress` which contains the shipping address may have some portions of its content altered, obscured, or left out entirely in order to prevent identifying the user without their consent (since if they choose to have you ship products to them, you'll need their address).

Example
-------

In this example, a handler for the `shippingaddresschange` event is set up to validate that the address meets requirements set by the web application.

```js
const paymentRequest = new PaymentRequest(methodData, details, options);

paymentRequest.addEventListener(
  "shippingaddresschange",
  (event) => {
    let detailsUpdate = checkAddress(paymentRequest.shippingAddress);
    event.updateWith(detailsUpdate);
  },
  false,
);

const checkAddress = (theAddress) => {
  let detailsUpdate = {};

  // Check the address, return an object with any changes or errors.

  return detailsUpdate;
};
```

You can also establish a handler for `shippingaddresschange` using the `onshippingaddresschange` event handler property:

```js
paymentRequest.onshippingaddresschange = (event) => {
  let detailsUpdate = checkAddress(paymentRequest.shippingAddress);
  event.updateWith(detailsUpdate);
};
```

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


ImageTrack: selected property - Web APIs

ImageTrack: selected property
=============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`selected`** property of the `ImageTrack` interface returns `true` if the track is selected for decoding.

Value
-----

A `boolean`, if `true` the track is selected for decoding.

Examples
--------

The following example prints the value of `selected` to the console.

```js
let track = imageDecoder.tracks.selectedTrack;
console.log(track.selected); // this is the selected track so should return true.
```

Specifications
--------------

| Specification |
| --- |
| WebCodecs # dom-imagetrack-selected |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


ImageTrack: repetitionCount property - Web APIs

ImageTrack: repetitionCount property
====================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`repetitionCount`** property of the `ImageTrack` interface returns the number of repetitions of this track.

Value
-----

An integer.

Examples
--------

The following example prints the value of `repetitionCount` to the console.

```js
let track = imageDecoder.tracks.selectedTrack;
console.log(track.repetitionCount);
```

Specifications
--------------

| Specification |
| --- |
| WebCodecs # dom-imagetrack-repetitioncount |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


ImageTrack: animated property - Web APIs

ImageTrack: animated property
=============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`animated`** property of the `ImageTrack` interface returns `true` if the track is animated and therefore has multiple frames.

Value
-----

A `boolean`, if `true` this is an animated track.

Examples
--------

The following example prints the value of `animated` to the console.

```js
let track = imageDecoder.tracks.selectedTrack;
console.log(track.animated);
```

Specifications
--------------

| Specification |
| --- |
| WebCodecs # dom-imagetrack-animated |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


ImageTrack: frameCount property - Web APIs

ImageTrack: frameCount property
===============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`frameCount`** property of the `ImageTrack` interface returns the number of frames in the track.

Value
-----

An integer.

Examples
--------

The following example prints the value of `frameCount` to the console.

```js
let track = imageDecoder.tracks.selectedTrack;
console.log(track.frameCount);
```

Specifications
--------------

| Specification |
| --- |
| WebCodecs # dom-imagetrack-framecount |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGGraphicsElement: cut event - Web APIs

SVGGraphicsElement: cut event
=============================

The **`cut`** event is fired on an `SVGGraphicsElement` when the user has initiated a "cut" action through the browser's user interface.

If the user attempts a cut action on uneditable content, the `cut` event still fires but the event object contains no data.

The event's default action is to copy the current selection (if any) to the system clipboard and remove it from the document.

A handler for this event can *modify* the clipboard contents by calling `setData(format, data)` on the event's `ClipboardEvent.clipboardData` property, and cancelling the default action using `event.preventDefault()`.

Note though that cancelling the default action will also prevent the document from being updated. So an event handler which wants to emulate the default action for "cut" while modifying the clipboard must also manually remove the selection from the document.

The handler cannot *read* the clipboard data.

It's possible to construct and dispatch a synthetic `cut` event, but this will not affect the system clipboard or the document's contents.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("cut", (event) => {});

oncut = (event) => {};
```

Event type
----------

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventSpecifications
--------------

| Specification |
| --- |
| Clipboard API and events # clipboard-event-cut |
| HTML Standard # handler-oncut |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related events: `copy`, `paste`
* This event on HTML `Element` targets: `cut`
* This event on `Document` targets: `cut`
* This event on `Window` targets: `cut`


SVGGraphicsElement: paste event - Web APIs

SVGGraphicsElement: paste event
===============================

The **`paste`** event is fired on an `SVGGraphicsElement` when the user has initiated a "paste" action through the browser's user interface.

If the cursor is in an editable context (for example, in a `<textarea>` or an element with `contenteditable` attribute set to `true`) then the default action is to insert the contents of the clipboard into the document at the cursor position.

A handler for this event can access the clipboard contents by calling `getData()` on the event's `clipboardData` property.

To override the default behavior (for example to insert some different data or a transformation of the clipboard contents) an event handler must cancel the default action using `event.preventDefault()`, and then insert its desired data manually.

It's possible to construct and dispatch a synthetic `paste` event, but this will not affect the document's contents.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("paste", (event) => {});

onpaste = (event) => {};
```

Event type
----------

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExample
-------

### HTML

```html
<?xml version="1.0" encoding="UTF-8"?>
<svg
 viewBox="0 0 140 30"
 width="600"
 height="320"
 xmlns="http://www.w3.org/2000/svg">
  <foreignObject x="5" y="-10" width="90" height="20">
    <input xmlns="http://www.w3.org/1999/xhtml" value="Copy this text" />
  </foreignObject>
  <text x="5" y="30" id="element-to-paste-text" tabindex="1">
    Paste it here
  </text>
</svg>
```

### CSS

```css
input {
  font-size: 10px;
  width: 100%;
  height: 90%;
  box-sizing: border-box;
  border: 1px solid black;
}
```

### JavaScript

```js
document
  .getElementById("element-to-paste-text")
  .addEventListener("paste", (evt) => {
    evt.target.textContent = evt.clipboardData
      .getData("text/plain")
      .toUpperCase();
    evt.preventDefault();
  });
```

### Result

Specifications
--------------

| Specification |
| --- |
| Clipboard API and events # clipboard-event-paste |
| HTML Standard # handler-onpaste |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related events: `cut`, `copy`
* This event on HTML `Element` targets: `paste`
* This event on `Document` targets: `paste`
* This event on `Window` targets: `paste`


SVGGraphicsElement: copy event - Web APIs

SVGGraphicsElement: copy event
==============================

The **`copy`** event fires on `SVGGraphicsElements` when the user initiates a copy action through the browser's user interface.

The event's default action is to copy the selection (if any) to the clipboard.

A handler for this event can *modify* the clipboard contents by calling `setData(format, data)` on the event's `ClipboardEvent.clipboardData` property, and cancelling the event's default action using `event.preventDefault()`.

However, the handler cannot *read* the clipboard data.

It's possible to construct and dispatch a synthetic `copy` event, but this will not affect the system clipboard.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("copy", (event) => {});

oncopy = (event) => {};
```

Event type
----------

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExample
-------

### HTML

```html
<?xml version="1.0" encoding="UTF-8"?>
<svg
 viewBox="0 0 100 30"
 width="600"
 height="320"
 xmlns="http://www.w3.org/2000/svg">
  <text x="5" y="10" id="text-to-copy">Copy this text</text>
  <foreignObject x="5" y="20" width="90" height="20">
    <input xmlns="http://www.w3.org/1999/xhtml" placeholder="Paste it here" />
  </foreignObject>
</svg>
```

### CSS

```css
input {
  font-size: 10px;
  width: 100%;
  height: 90%;
  box-sizing: border-box;
  border: 1px solid black;
}
```

### JavaScript

```js
document.querySelector("text").addEventListener("copy", (evt) => {
  evt.clipboardData.setData(
    "text/plain",
    document.getSelection().toString().toUpperCase(),
  );
  evt.preventDefault();
});
```

### Result

Specifications
--------------

| Specification |
| --- |
| Clipboard API and events # clipboard-event-copy |
| HTML Standard # handler-oncopy |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Related events: `cut`, `paste`
* This event on HTML `Element` targets: `copy`
* This event on `Document` targets: `copy`
* This event on `Window` targets: `copy`


SVGGraphicsElement: getBBox() method - Web APIs

SVGGraphicsElement: getBBox() method
====================================

 The **`SVGGraphicsElement.getBBox()`** method allows us to determine
 the coordinates of the smallest rectangle in which the object fits. The coordinates
 returned are with respect to the current SVG space (after the application of all
 geometry attributes on all the elements contained in the target element).

**Note:** `getBBox()` must return the actual bounding box at
 the time the method was called—even in case the element has not yet been rendered. It
 also does not account for any transformation applied to the element or its parents.

**Note:** `getBBox` returns different values than
 `getBoundingClientRect()`, as the
 latter returns value relative to the viewport

Syntax
------

```js
getBBox()
getBBox(options)
```

### Parameters

`options`
Experimental
 Optional

 An options dictionary used to control which parts of the element are included in the
 bounding box. The available options are:

`fill`

 A boolean value indicating that the fill should be included in the bounding box,
 defaults to `true`.

`stroke`

 A boolean value indicating that the stroke should be included in the bounding
 box, defaults to `false`.

`markers`

 A boolean value indicating that the markers should be included in the bounding
 box, defaults to `false`.

`clipped`

 A boolean value indicating that the bounding box should be clipped, defaults to
 `false`.

### Return value

 The returned value is a `SVGRect` object, which defines the bounding box.
 This value is irrespective of any transformation attribute applied to it or the parent
 elements.

Examples
--------

### HTML

```html
<svg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
  <g id="group\_text\_1">
    <text x="5" y="16" transform="scale(2, 2)">Hello World!</text>
    <text x="8" y="32" transform="translate(0 20) scale(1.25 1)">
      Hello World Again!
    </text>
  </g>
  <!-- Shows BBox in green -->
  <rect id="rect\_1" stroke="#00ff00" stroke-width="3" fill="none"></rect>
  <!-- Shows BoundingClientRect in red -->
  <rect id="rect\_2" stroke="#ff0000" stroke-width="3" fill="none"></rect>
</svg>
```

### JavaScript

```js
const rectBBox = document.querySelector("#rect\_1");
const rectBoundingClientRect = document.querySelector("#rect\_2");
const groupElement = document.querySelector("#group\_text\_1");

const bboxGroup = groupElement.getBBox();
rectBBox.setAttribute("x", bboxGroup.x);
rectBBox.setAttribute("y", bboxGroup.y);
rectBBox.setAttribute("width", bboxGroup.width);
rectBBox.setAttribute("height", bboxGroup.height);

const boundingClientRectGroup = groupElement.getBoundingClientRect();
rectBoundingClientRect.setAttribute("x", boundingClientRectGroup.x);
rectBoundingClientRect.setAttribute("y", boundingClientRectGroup.y);
rectBoundingClientRect.setAttribute("width", boundingClientRectGroup.width);
rectBoundingClientRect.setAttribute("height", boundingClientRectGroup.height);
```

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # \_\_svg\_\_SVGGraphicsElement\_\_getBBox |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* getBBox in SVG Primer


IntersectionObserverEntry: intersectionRatio property - Web APIs

IntersectionObserverEntry: intersectionRatio property
=====================================================

 The `IntersectionObserverEntry` interface's
 read-only **`intersectionRatio`** property tells you how much
 of the target element is currently visible within the root's intersection ratio, as a
 value between 0.0 and 1.0.

Value
-----

 A number between 0.0 and 1.0 which indicates how much of the target element is actually
 visible within the root's intersection rectangle. More precisely, this value is the
 ratio of the area of the intersection rectangle
 (`intersectionRect`) to the
 area of the target's bounds rectangle
 (`boundingClientRect`).

 If the area of the target's bounds rectangle is zero, the returned value is 1 if
 `isIntersecting` is
 `true` or 0 if not.

Examples
--------

 In this simple example, an intersection callback sets each target element's
 `opacity` to the intersection ratio of that element with the root.

```js
function intersectionCallback(entries) {
  entries.forEach((entry) => {
    entry.target.style.opacity = entry.intersectionRatio;
  });
}
```

 To see a more concrete example, take a look at
 Handling intersection changes.

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserverentry-intersectionratio |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


IntersectionObserverEntry: intersectionRect property - Web APIs

IntersectionObserverEntry: intersectionRect property
====================================================

 The `IntersectionObserverEntry` interface's
 read-only **`intersectionRect`** property is a
 `DOMRectReadOnly` object which describes the smallest rectangle that
 contains the entire portion of the target element which is currently visible within
 the intersection root.

Value
-----

 A `DOMRectReadOnly` which describes the part of the target element that's
 currently visible within the root's intersection rectangle.

 This rectangle is computed by taking the intersection of
 `boundingClientRect` with each of the
 `target`'s ancestors' clip rectangles,
 with the exception of the intersection `root`
 itself.

Examples
--------

 In this simple example, an intersection callback stores the intersection rectangle for
 later use by the code that draws the target elements' contents, so that only the visible
 area is redrawn.

```js
function intersectionCallback(entries) {
  entries.forEach((entry) => {
    refreshZones.push({
      element: entry.target,
      rect: entry.intersectionRect,
    });
  });
}
```

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserverentry-intersectionrect |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


IntersectionObserverEntry: rootBounds property - Web APIs

IntersectionObserverEntry: rootBounds property
==============================================

 The `IntersectionObserverEntry` interface's
 read-only **`rootBounds`** property is a
 `DOMRectReadOnly` corresponding to the
 `target`'s root intersection
 rectangle, offset by the `IntersectionObserver.rootMargin` if one is
 specified.

Value
-----

 A `DOMRectReadOnly` which describes the root intersection rectangle. For
 roots which are the `Document`'s viewport, this rectangle is the bounds
 rectangle of the entire document. Otherwise, it's the bounds of the root element.

 This rectangle is offset by the values in
 `IntersectionObserver.rootMargin`.

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserverentry-rootbounds |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


IntersectionObserverEntry: boundingClientRect property - Web APIs

IntersectionObserverEntry: boundingClientRect property
======================================================

 The `IntersectionObserverEntry` interface's read-only
 **`boundingClientRect`** property returns a
 `DOMRectReadOnly` which in essence describes a rectangle describing the
 smallest rectangle that contains the entire target element.

Value
-----

 A `DOMRectReadOnly` which describes the smallest rectangle that contains
 every part of the target element whose intersection change is being described. This
 value is obtained using the same algorithm as
 `Element.getBoundingClientRect()`, so refer to that article for details on
 precisely what is done to obtain this rectangle and what is and is not included within
 its bounds.

 In the general case, however, it's safe to think of this as the bounds rectangle of the
 target element.

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserverentry-boundingclientrect |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


IntersectionObserverEntry: isIntersecting property - Web APIs

IntersectionObserverEntry: isIntersecting property
==================================================

 The `IntersectionObserverEntry` interface's
 read-only **`isIntersecting`** property is a Boolean value
 which is `true` if the target element intersects with the intersection
 observer's root. If this is `true`, then, the
 `IntersectionObserverEntry` describes a transition into a state of
 intersection; if it's `false`, then you know the transition is from
 intersecting to not-intersecting.

Value
-----

 A Boolean value which indicates whether the
 `target` element has transitioned into
 a state of intersection (`true`) or out of a state of intersection
 (`false`).

Examples
--------

 In this simple example, an intersection callback is used to update a counter of how
 many targeted elements are currently intersecting with the
 intersection root.

```js
function intersectionCallback(entries) {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      intersectingCount += 1;
    } else {
      intersectingCount -= 1;
    }
  });
}
```

 To see a more concrete example, take a look at
 Handling intersection changes.

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserverentry-isintersecting |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


IntersectionObserverEntry: target property - Web APIs

IntersectionObserverEntry: target property
==========================================

 The `IntersectionObserverEntry` interface's
 read-only **`target`** property indicates which targeted
 `Element` has changed its amount of intersection with the intersection
 root.

Value
-----

 The `IntersectionObserverEntry`'s `target` property specifies
 which `Element` previously targeted by calling
 `IntersectionObserver.observe()` experienced a change in intersection with
 the root.

Examples
--------

 In this simple example, each targeted element's `opacity` is set to its
 `intersectionRatio`.

```js
function intersectionCallback(entries) {
  entries.forEach((entry) => {
    entry.target.style.opacity = entry.intersectionRatio;
  });
}
```

 To see a more concrete example, take a look at
 Handling intersection changes.

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserverentry-target |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


IntersectionObserverEntry: time property - Web APIs

IntersectionObserverEntry: time property
========================================

 The `IntersectionObserverEntry` interface's
 read-only **`time`** property is a
 `DOMHighResTimeStamp` that indicates the time at which the intersection
 change occurred relative to the time at which the document was created.

Value
-----

 A `DOMHighResTimeStamp` which indicates the time at which the
 `target` element experienced the
 intersection change described by the `IntersectionObserverEntry`. The time is
 specified in milliseconds since the creation of the containing document.

Examples
--------

 See Timing element visibility with the Intersection Observer API for a complete example which
 uses the `time` property to track how long elements are visible to the user.

Specifications
--------------

| Specification |
| --- |
| Intersection Observer # dom-intersectionobserverentry-time |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Using the Geolocation API - Web APIs

Using the Geolocation API
=========================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

The Geolocation API is used to retrieve the user's location, so that it can for example be used to display their position using a mapping API. This article explains the basics of how to use it.

The geolocation object
----------------------

The Geolocation API is available through the `navigator.geolocation` object.

If the object exists, geolocation services are available. You can test for the presence of geolocation thusly:

```js
if ("geolocation" in navigator) {
  /\* geolocation is available \*/
} else {
  /\* geolocation IS NOT available \*/
}
```

### Getting the current position

To obtain the user's current location, you can call the `getCurrentPosition()` method. This initiates an asynchronous request to detect the user's position, and queries the positioning hardware to get up-to-date information. When the position is determined, the defined callback function is executed. You can optionally provide a second callback function to be executed if an error occurs. A third, optional, parameter is an options object where you can set the maximum age of the position returned, the time to wait for a request, and if you want high accuracy for the position.

**Note:** By default, `getCurrentPosition()` tries to answer as fast as possible with a low accuracy result. It is useful if you need a quick answer regardless of the accuracy. Devices with a GPS, for example, can take a minute or more to get a GPS fix, so less accurate data (IP location or Wi-Fi) may be returned to `getCurrentPosition()`.

```js
navigator.geolocation.getCurrentPosition((position) => {
  doSomething(position.coords.latitude, position.coords.longitude);
});
```

The above example will cause the `doSomething()` function to execute when the location is obtained.

### Watching the current position

If the position data changes (either by device movement or if more accurate geo information arrives), you can set up a callback function that is called with that updated position information. This is done using the `watchPosition()` function, which has the same input parameters as `getCurrentPosition()`. The callback function is called multiple times, allowing the browser to either update your location as you move, or provide a more accurate location as different techniques are used to geolocate you. The error callback function, which is optional just as it is for `getCurrentPosition()`, can be called repeatedly.

**Note:** You can use `watchPosition()` without an initial `getCurrentPosition()` call.

```js
const watchID = navigator.geolocation.watchPosition((position) => {
  doSomething(position.coords.latitude, position.coords.longitude);
});
```

The `watchPosition()` method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the `clearWatch()` method to stop watching the user's location.

```js
navigator.geolocation.clearWatch(watchID);
```

### Fine tuning the response

Both `getCurrentPosition()` and `watchPosition()` accept a success callback, an optional error callback, and an optional options object.

This object allows you to specify whether to enable high accuracy, a maximum age for the returned position value (up until this age it will be cached and reused if the same position is requested again; after this the browser will request fresh position data), and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out.

A call to `watchPosition` could look like:

```js
function success(position) {
  doSomething(position.coords.latitude, position.coords.longitude);
}

function error() {
  alert("Sorry, no position available.");
}

const options = {
  enableHighAccuracy: true,
  maximumAge: 30000,
  timeout: 27000,
};

const watchID = navigator.geolocation.watchPosition(success, error, options);
```

Describing a position
---------------------

The user's location is described using a `GeolocationPosition` object instance, which itself contains a `GeolocationCoordinates` object instance.

The `GeolocationPosition` instance contains only two things, a `coords` property that contains the `GeolocationCoordinates` instance, and a `timestamp` property that contains a timestamp, given as Unix time in milliseconds, at which the position data was retrieved.

The `GeolocationCoordinates` instance contains a number of properties, but the two you'll use most commonly are `latitude` and `longitude`, which are what you need to draw your position on a map. Hence many Geolocation success callbacks look fairly simple:

```js
function success(position) {
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;

  // Do something with your latitude and longitude
}
```

You can however get a number of other bits of information from a `GeolocationCoordinates` object, including altitude, speed, what direction the device is facing, and an accuracy measure of the altitude, longitude, and latitude data.

Handling errors
---------------

The error callback function, if provided when calling `getCurrentPosition()` or `watchPosition()`, expects a `GeolocationPositionError` object instance as its first parameter. This object type contains two properties, a `code` indicating what type of error has been returned, and a human-readable `message` that describes what the error code means.

You could use it like so:

```js
function errorCallback(error) {
  alert(`ERROR(${error.code}): ${error.message}`);
}
```

Examples
--------

In the following example the Geolocation API is used to retrieve the user's latitude and longitude. If successful, the available hyperlink is populated with an `openstreetmap.org` URL that will show their location.
```

body {
  padding: 20px;
  background-color: #ffffc9;
}

button {
  margin: 0.5rem 0;
}
```

### HTML

```html
<button id="find-me">Show my location</button><br />
<p id="status"></p>
<a id="map-link" target="\_blank"></a>
```

### JavaScript

```js
function geoFindMe() {
  const status = document.querySelector("#status");
  const mapLink = document.querySelector("#map-link");

  mapLink.href = "";
  mapLink.textContent = "";

  function success(position) {
    const latitude = position.coords.latitude;
    const longitude = position.coords.longitude;

    status.textContent = "";
    mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
    mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
  }

  function error() {
    status.textContent = "Unable to retrieve your location";
  }

  if (!navigator.geolocation) {
    status.textContent = "Geolocation is not supported by your browser";
  } else {
    status.textContent = "Locating…";
    navigator.geolocation.getCurrentPosition(success, error);
  }
}

document.querySelector("#find-me").addEventListener("click", geoFindMe);
```

### Result


FormDataEvent: FormDataEvent() constructor - Web APIs

FormDataEvent: FormDataEvent() constructor
==========================================

The **`FormDataEvent()`** constructor creates a new `FormDataEvent` object.

Syntax
------

```js
new FormDataEvent(type, formEventInit)
```

### Parameters

`type`

 A string with the name of the event.
 It is case-sensitive and browsers always set it to `formdata`.

`options`

An object that, *in addition of the properties defined in `Event()`*, can have the following properties:

`formData`

 A `FormData` object to pre-populate the `FormDataEvent` with.
 This would then be accessed through the `FormDataEvent.formData` property.

### Return value

A new `FormDataEvent` object.

Examples
--------

```js
const fd = new FormData();
fd.append("test", "test");

const fdEv = new FormDataEvent("formdata", { formData: fd });

for (const value of fdEv.formData.values()) {
  console.log(value);
}
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-formdataevent-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `FormDataEvent`


FormDataEvent: formData property - Web APIs

FormDataEvent: formData property
================================

 The `formData` read-only property of the `FormDataEvent`
 interface contains the `FormData` object representing the data contained in
 the form when the event was fired.

Value
-----

A `FormData` object.

Examples
--------

```js
// grab reference to form

const formElem = document.querySelector("form");

// submit handler

formElem.addEventListener("submit", (e) => {
  // on form submission, prevent default
  e.preventDefault();

  // construct a FormData object, which fires the formdata event
  new FormData(formElem);
});

// formdata handler to retrieve data

formElem.addEventListener("formdata", (e) => {
  console.log("formdata fired");

  // Get the form data from the event object
  let data = e.formData;
  for (const value of data.values()) {
    console.log(value);
  }

  // submit the data via XHR
  const request = new XMLHttpRequest();
  request.open("POST", "/formHandler");
  request.send(data);
});
```

Specifications
--------------

| Specification |
| --- |
| HTML Standard # the-formdataevent-interface:dom-formdataevent-formdata-2 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `XMLHTTPRequest`
* Using XMLHttpRequest
* Using FormData objects
* `<form>`


BiquadFilterNode: gain property - Web APIs

BiquadFilterNode: gain property
===============================

The `gain` property of the `BiquadFilterNode` interface is an a-rate `AudioParam` — a double representing the gain used in the current filtering algorithm.

When its value is positive, it represents a real gain; when negative, it represents an attenuation.

It is expressed in dB, has a default value of `0`, and can take a value in a nominal range of `-40` to `40`.

Value
-----

An `AudioParam`.

**Note:** Though the `AudioParam` returned is read-only, the value it represents is not.

Examples
--------

 The following example shows basic usage of an AudioContext to create a Biquad filter node.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new AudioContext();

//set up the different audio nodes we will use for the app
const analyser = audioCtx.createAnalyser();
const distortion = audioCtx.createWaveShaper();
const gainNode = audioCtx.createGain();
const biquadFilter = audioCtx.createBiquadFilter();
const convolver = audioCtx.createConvolver();

// connect the nodes together

source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(convolver);
convolver.connect(gainNode);
gainNode.connect(audioCtx.destination);

// Manipulate the Biquad filter

biquadFilter.type = "lowshelf";
biquadFilter.frequency.value = 1000;
biquadFilter.gain.value = 25;
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-biquadfilternode-gain |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BiquadFilterNode: type property - Web APIs

BiquadFilterNode: type property
===============================

The `type` property of the `BiquadFilterNode` interface is a string (enum) value defining the kind of filtering algorithm the node is implementing.

Value
-----

A string (enum) representing a BiquadFilterType.

`type` values and their meaning
-------------------------------

| `type` | Description | `frequency` | `Q` | `gain` |
| --- | --- | --- | --- | --- |
| `lowpass` |
 Standard second-order resonant lowpass filter with 12dB/octave rolloff.
 Frequencies below the cutoff pass through; frequencies above it are
 attenuated.
  | The cutoff frequency. |
 Indicates how peaked the frequency is around the cutoff. The greater the
 value is, the greater is the peak.
  | *Not used* |
| `highpass` |
 Standard second-order resonant highpass filter with 12dB/octave rolloff.
 Frequencies below the cutoff are attenuated; frequencies above it pass
 through.
  | The cutoff frequency. |
 Indicates how peaked the frequency is around the cutoff. The greater the
 value, the greater the peak.
  | *Not used* |
| `bandpass` |
 Standard second-order bandpass filter. Frequencies outside the given
 range of frequencies are attenuated; the frequencies inside it pass
 through.
  | The center of the range of frequencies. |
 Controls the width of the frequency band. The greater the
 `Q` value, the larger the frequency band.
  | *Not used* |
| `lowshelf` |
 Standard second-order lowshelf filer. Frequencies lower than the
 frequency get a boost, or an attenuation; frequencies over it are
 unchanged.
  | The upper limit of the frequencies getting a boost or an attenuation. | *Not used* | The boost, in dB, to be applied; if negative, it will be an attenuation. |
| `highshelf` |
 Standard second-order highshelf filer. Frequencies higher than the
 frequency get a boost or an attenuation; frequencies lower than it are
 unchanged.
  | The lower limit of the frequencies getting a boost or an attenuation. | *Not used* | The boost, in dB, to be applied; if negative, it will be an attenuation. |
| `peaking` |
 Frequencies inside the range get a boost or an attenuation; frequencies
 outside it are unchanged.
  | The middle of the frequency range getting a boost or an attenuation. |
 Controls the width of the frequency band. The greater the
 `Q` value, the larger the frequency band.
  | The boost, in dB, to be applied; if negative, it will be an attenuation. |
| `notch` |
 Standard
 notch
 filter, also called a *band-stop* or
 *band-rejection* filter. It is the opposite of a bandpass filter:
 frequencies outside the give range of frequencies pass through;
 frequencies inside it are attenuated.
  | The center of the range of frequencies. |
 Controls the width of the frequency band. The greater the
 `Q` value, the larger the frequency band.
  | *Not used* |
| `allpass` |
 Standard second-order
 allpass
 filter. It Lets all frequencies through, but changes the
 phase-relationship between the various frequencies.
  |
 The frequency with the maximal
 group delay, that is, the frequency where the center of the phase transition
 occurs.
  |
 Controls how sharp the transition is at the medium frequency. The larger
 this parameter is, the sharper and larger the transition will be.
  | *Not used* |

Examples
--------

 The following example shows basic usage of an AudioContext to create a Biquad filter node.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new AudioContext();

//set up the different audio nodes we will use for the app
const analyser = audioCtx.createAnalyser();
const distortion = audioCtx.createWaveShaper();
const gainNode = audioCtx.createGain();
const biquadFilter = audioCtx.createBiquadFilter();
const convolver = audioCtx.createConvolver();

// connect the nodes together

source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(convolver);
convolver.connect(gainNode);
gainNode.connect(audioCtx.destination);

// Manipulate the Biquad filter

biquadFilter.type = "lowshelf";
biquadFilter.frequency.value = 1000;
biquadFilter.gain.value = 25;
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-biquadfilternode-type |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BiquadFilterNode: Q property - Web APIs

BiquadFilterNode: Q property
============================

The `Q` property of the `BiquadFilterNode` interface is an a-rate `AudioParam`, a double representing a Q factor, or *quality factor*.

It is a dimensionless value with a default value of `1` and a nominal range of `0.0001` to `1000`.

Value
-----

An `AudioParam`.

**Note:** Though the `AudioParam` returned is read-only, the value it represents is not.

Examples
--------

 The following example shows basic usage of an AudioContext to create a Biquad filter node.
 For more complete applied examples/information, check out our Voice-change-O-matic demo (see app.js lines 108–193 for relevant code).

```js
const audioCtx = new AudioContext();

//set up the different audio nodes we will use for the app
const analyser = audioCtx.createAnalyser();
const distortion = audioCtx.createWaveShaper();
const gainNode = audioCtx.createGain();
const biquadFilter = audioCtx.createBiquadFilter();
const convolver = audioCtx.createConvolver();

// connect the nodes together

source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(convolver);
convolver.connect(gainNode);
gainNode.connect(audioCtx.destination);

// Manipulate the Biquad filter

biquadFilter.type = "lowshelf";
biquadFilter.frequency.value = 1000;
biquadFilter.gain.value = 25;

biquadFilter.type = "peaking";
biquadFilter.frequency.value = 1000;
biquadFilter.Q.value = 100;
biquadFilter.gain.value = 25;
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-biquadfilternode-q |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BiquadFilterNode: frequency property - Web APIs

BiquadFilterNode: frequency property
====================================

The `frequency` property of the `BiquadFilterNode` interface is an a-rate `AudioParam` — a double representing a frequency in the current filtering algorithm measured in hertz (Hz).

Its default value is `350`, with a nominal range of `10` to the Nyquist frequency — that is, half of the sample rate.

Value
-----

An `AudioParam`.

**Note:** Though the `AudioParam` returned is read-only, the value it represents is not.

Examples
--------

 The following example shows basic usage of an AudioContext to create a Biquad filter node.
 For a complete working example, check out our voice-change-o-matic demo (look at the source code too).

```js
const audioCtx = new AudioContext();

//set up the different audio nodes we will use for the app
const analyser = audioCtx.createAnalyser();
const distortion = audioCtx.createWaveShaper();
const gainNode = audioCtx.createGain();
const biquadFilter = audioCtx.createBiquadFilter();
const convolver = audioCtx.createConvolver();

// connect the nodes together

source = audioCtx.createMediaStreamSource(stream);
source.connect(analyser);
analyser.connect(distortion);
distortion.connect(biquadFilter);
biquadFilter.connect(convolver);
convolver.connect(gainNode);
gainNode.connect(audioCtx.destination);

// Manipulate the Biquad filter

biquadFilter.type = "lowshelf";
biquadFilter.frequency.value = 1000;
biquadFilter.gain.value = 25;
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-biquadfilternode-frequency |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API


BiquadFilterNode: getFrequencyResponse() method - Web APIs

BiquadFilterNode: getFrequencyResponse() method
===============================================

 The `getFrequencyResponse()` method of the `BiquadFilterNode` interface takes the current filtering algorithm's settings and calculates the
 frequency response for frequencies specified in a specified array of frequencies.

 The two output arrays, `magResponseOutput` and
 `phaseResponseOutput`, must be created before calling this method; they
 must be the same size as the array of input frequency values
 (`frequencyArray`).

Syntax
------

```js
getFrequencyResponse(frequencyArray, magResponseOutput, phaseResponseOutput)
```

### Parameters

`frequencyArray`

 A `Float32Array` containing an array of frequencies, specified in Hertz,
 which you want to filter.

`magResponseOutput`

 A `Float32Array` to receive the computed magnitudes of the frequency
 response for each frequency value in the `frequencyArray`. For any
 frequency in `frequencyArray` whose value is outside the range 0.0 to
 `sampleRate`/2 (where `sampleRate`
 is the sample rate of the `AudioContext`), the corresponding value in
 this array is `NaN`. These are unitless values.

`phaseResponseOutput`

 A `Float32Array` to receive the computed phase response values in
 radians for each frequency value in the input `frequencyArray`. For any
 frequency in `frequencyArray` whose value is outside the range 0.0 to
 `sampleRate`/2 (where `sampleRate`
 is the sample rate of the `AudioContext`), the corresponding value in
 this array is `NaN`.

### Return value

None (`undefined`).

### Exceptions

`InvalidAccessError`

The three arrays provided are not all of the same length.

Examples
--------

 In the following example we are using a biquad filter on a media stream (for the full
 demo, see our stream-source-buffer demo live, or read the source.) As part of this demo, we get the frequency responses for this biquad
 filter, for five sample frequencies. We first create the `Float32Array`s we
 need, one containing the input frequencies, and two to receive the output magnitude and
 phase values:

```js
const myFrequencyArray = new Float32Array(5);
myFrequencyArray[0] = 1000;
myFrequencyArray[1] = 2000;
myFrequencyArray[2] = 3000;
myFrequencyArray[3] = 4000;
myFrequencyArray[4] = 5000;

const magResponseOutput = new Float32Array(5);
const phaseResponseOutput = new Float32Array(5);
```

 Next we create a `<ul>` element in our HTML to contain our results,
 and grab a reference to it in our JavaScript:

```html
<p>Biquad filter frequency response for:</p>
<ul class="freq-response-output"></ul>
```

```js
const freqResponseOutput = document.querySelector(".freq-response-output");
```

 Finally, after creating our biquad filter, we use `getFrequencyResponse()`
 to generate the response data and put it in our arrays, then loop through each data set
 and output them in a human-readable list at the bottom of the page:

```js
const biquadFilter = audioCtx.createBiquadFilter();
biquadFilter.type = "lowshelf";
biquadFilter.frequency.value = 1000;
biquadFilter.gain.value = range.value;

// …

function calcFrequencyResponse() {
  biquadFilter.getFrequencyResponse(
    myFrequencyArray,
    magResponseOutput,
    phaseResponseOutput,
  );

  for (let i = 0; i <= myFrequencyArray.length - 1; i++) {
    const listItem = document.createElement("li");
    listItem.innerHTML = `<strong>${myFrequencyArray[i]}Hz</strong>: Magnitude ${magResponseOutput[i]}, Phase ${phaseResponseOutput[i]} radians.`;
    freqResponseOutput.appendChild(listItem);
  }
}

calcFrequencyResponse();
```

Specifications
--------------

| Specification |
| --- |
| Web Audio API # dom-biquadfilternode-getfrequencyresponse |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using the Web Audio API