# Elements and Events

This section details the various Elements available for use in your Stripe integrations, along with their associated events and methods.

## Element Events

Elements can emit various events that allow you to react to user interactions and state changes.

### `change` Event

The `change` event is triggered when any value within an Element's payload changes. The payload consistently includes certain keys, along with Element-specific ones.

**Supported Elements:** `paymentElement`, `billingAddressElement`, `shippingAddressElement`, and `taxIdElement`.

```javascript
element.on('change', (event) => {
  // Handle the change event
  console.log(event);
});
```

### `ready` Event

The `ready` event fires when an Element is fully rendered and ready for interaction. Methods like `focus()` and `update()` can be called after this event.

```javascript
element.on('ready', (event) => {
  // Handle the ready event
  console.log(event.elementType); // The type of element that fired the event
});
```

### `focus` Event

The `focus` event is triggered when an Element gains focus.

```javascript
element.on('focus', (event) => {
  // Handle the focus event
  console.log(event.elementType); // The type of element that fired the event
});
```

### `blur` Event

The `blur` event is triggered when an Element loses focus.

```javascript
element.on('blur', (event) => {
  // Handle the blur event
  console.log(event.elementType); // The type of element that fired the event
});
```

### `escape` Event

The `escape` event is triggered when the escape key is pressed within an Element.

```javascript
element.on('escape', (event) => {
  // Handle the escape event
  console.log(event.elementType); // The type of element that fired the event
});
```

### `loaderror` Event

The `loaderror` event is triggered when an Element fails to load.

```javascript
element.on('loaderror', (event) => {
  // Handle the loaderror event
  console.log(event.elementType); // The type of element that fired the event
  console.log(event.error);      // The error object
});
```

## Express Checkout Element Events

The Express Checkout Element has specific events for handling payment confirmation and cancellation.

### `confirm` Event

The `confirm` event is triggered when a customer finalizes their payment through the Express Checkout Element. This event is used to confirm the payment.

```javascript
expressCheckoutElement.on('confirm', (event) => {
  // Handle the confirm event
  console.log(event.elementType);
  console.log(event.expressPaymentType);
  event.paymentFailed({ reason: 'fail', message: 'Payment failed.' }); // Call if payment processing fails
});
```

### `cancel` Event

The `cancel` event is triggered when the payment interface is dismissed. This can happen even after payment authorization.

```javascript
expressCheckoutElement.on('cancel', (event) => {
  // Handle the cancel event
  console.log('Payment interface dismissed.');
});
```

## Other Element Methods

### `blur()`

Blurs the Element.

```javascript
element.blur();
```

### `update-end` Event

The `update-end` event is triggered when the `elements.update()` call is complete.

```javascript
elements.on('update-end', () => {
  // Handle the update-end event
});
```

## Retrieving and Creating Elements

### `elements.getElement(type)`

Retrieves a previously created Element.

```javascript
const paymentElement = elements.getElement('payment');
const expressCheckoutElement = elements.getElement('expressCheckout');
const linkAuthenticationElement = elements.getElement('linkAuthentication');
const addressElement = elements.getElement('address', { mode: 'shipping' }); // Mode is required for multiple Address Elements
const taxIdElement = elements.getElement('taxId');
```

### `elements.create(type, options)`

Creates an instance of an Element.

```javascript
const expressCheckoutElement = elements.create('expressCheckout', {
  allowedShippingCountries: ['US', 'CA'],
  applePay: { /* Apple Pay specific options */ },
  recurringPaymentRequest: { /* Recurring payment options */ },
  deferredPaymentRequest: { /* Deferred payment options */ },
  automaticReloadPaymentRequest: { /* Automatic reload payment options */ },
  billingAddressRequired: true,
});

const linkAuthenticationElement = elements.create('linkAuthentication', {
  defaultValues: {
    email: 'test@example.com',
  },
});

const addressElement = elements.create('address');
const taxIdElement = elements.create('taxId');
```

## Payment Element Methods

### `element.collapse()`

Collapses the Payment Element into a row of payment method tabs.

```javascript
paymentElement.collapse();
```

### `element.getValue()`

Validates and retrieves form values from a Tax ID Element. Input validation errors are displayed by their associated fields.

```javascript
const taxIdValue = taxIdElement.getValue();
```

## Express Checkout Element Specifics

### Express Checkout Element

An embeddable component for accepting payments through one-click payment buttons.

### Express Checkout Element Options

When creating an Express Checkout Element, you can provide various options:

*   `allowedShippingCountries`: Specify allowed shipping countries using two-letter country codes.
*   `applePay`: Options for Apple Pay.
*   `recurringPaymentRequest`: Options for recurring payments.
*   `paymentDescription`: Description for the payment.
*   `managementURL`: URL for management.
*   `regularBilling`: Options for regular billing.
*   `amount`: The amount for recurring or trial billing.
*   `label`: Label for recurring or trial billing.
*   `recurringPaymentStartDate`: Start date for recurring payments.
*   `recurringPaymentEndDate`: End date for recurring payments.
*   `recurringPaymentIntervalUnit`: Unit for recurring payment interval.
*   `recurringPaymentIntervalCount`: Count for recurring payment interval.
*   `trialBilling`: Options for trial billing.
*   `billingAgreement`: Billing agreement details.
*   `deferredPaymentRequest`: Options for deferred payments.
*   `amountType`: Indicates if the billing amount is known at request time ('final').
*   `deferredBilling`: Options for deferred billing.
*   `deferredPaymentDate`: Date for deferred payment.
*   `freeCancellationDate`: Date for free cancellation.
*   `freeCancellationDateTimeZone`: Timezone for free cancellation date.
*   `automaticReloadPaymentRequest`: Options for automatic reload payments.
*   `automaticReloadBilling`: Options for automatic reload billing.
*   `automaticReloadPaymentThresholdAmount`: Threshold amount for automatic reload.
*   `lineItems`: An array of LineItem objects to be displayed in the payment interface.
    *   `name`: Name of the line item.
    *   `amount`: Amount of the line item.
*   `billingAddressRequired`: Controls whether the billing address is collected.

## Address Element

An embeddable component for collecting local and international billing and shipping addresses.

## Embedded Checkout

### `checkout.mount(domElement)`

Attaches Checkout to the DOM. Accepts a CSS selector or a DOM element.

```javascript
checkout.mount('#checkout-container');
```

### `checkout.unmount()`

Unmounts Checkout from the DOM.

```javascript
checkout.unmount();
```

### `checkout.destroy()`

Removes Checkout from the DOM and destroys it.

```javascript
checkout.destroy();
```

## Custom Checkout

### Actions

The `actions` object provides methods for interacting with the Checkout Session.

*   `actions.getSession()`: Reads session data.
*   `actions.applyPromotionCode(promotionCode)`: Applies a promotion code.
*   `actions.removePromotionCode()`: Removes the currently applied promotion code.
*   `actions.updateShippingAddress(shippingAddress)`: Updates the customer's shipping address.
*   `actions.updateBillingAddress(billingAddress)`: Updates the customer's billing address.
*   `actions.updateEmail(email)`: Updates the customer's email address.
*   `actions.updatePhoneNumber(phoneNumber)`: Updates the customer's phone number.
*   `actions.updateTaxIdInfo(taxIdInfo)`: Updates the customer's business name and tax ID.
*   `actions.updateLineItemQuantity(options)`: Updates the quantity of a line item.
*   `actions.updateShippingOption(shippingOption)`: Updates the selected shipping option.
*   `actions.runServerUpdate(userFunction)`: Wraps an async function that updates the Checkout Session on your server.

### Checkout Events

Listen to Checkout events to respond to changes on your checkout page.

#### `change` Event

Triggered when Checkout Session data changes (e.g., shipping address update). The event payload is a Checkout Session object.

```javascript
checkout.on('change', (session) => {
  // Handle the change event
  console.log(session);
});
```

### Creating Elements

*   `checkout.createBillingAddressElement(options)`: Creates a Billing Address Element.
*   `checkout.createShippingAddressElement(options)`: Creates a Shipping Address Element.
*   `checkout.createCurrencySelectorElement()`: Creates a Currency Selector Element.

### Getting Elements

*   `checkout.getPaymentElement()`: Gets the Payment Element instance.
*   `checkout.getBillingAddressElement()`: Gets the Billing Address Element instance.
*   `checkout.getShippingAddressElement()`: Gets the Shipping Address Element instance.
*   `checkout.getExpressCheckoutElement()`: Gets the Express Checkout Element instance.
*   `checkout.getCurrencySelectorElement()`: Gets the Currency Selector Element instance.

### Appearance and Fonts

*   `checkout.changeAppearance(appearance)`: Changes the visual customization of Elements using the Appearance API.
*   `checkout.loadFonts(fonts)`: Loads additional custom fonts into Elements.

## React Stripe.js Checkout

### Checkout Actions

The React Stripe.js `checkout` object provides methods for interacting with the Checkout Session.

*   `applyPromotionCode(promotionCode)`: Applies a promotion code.
*   `removePromotionCode()`: Removes the currently applied promotion code.
*   `updateShippingAddress(shippingAddress)`: Updates the customer's shipping address.
*   `updateBillingAddress(billingAddress)`: Updates the customer's billing address.
*   `updateEmail(email)`: Updates the customer's email address.
*   `updatePhoneNumber(phoneNumber)`: Updates the customer's phone number.
*   `updateTaxIdInfo(taxIdInfo)`: Updates the customer's business name and tax ID.
*   `updateLineItemQuantity(options)`: Updates the quantity of a line item.
*   `updateShippingOption(shippingOption)`: Updates the selected shipping option.
*   `runServerUpdate(userFunction)`: Wraps an async function that updates the Checkout Session on your server.

## Payment Request Events

`PaymentRequest` instances emit various types of events.

## Viewport Meta Tag Requirements

To ensure a great user experience for 3D Secure on all devices, set your page's viewport `width` to `device-width` using the viewport meta tag.

```html
<meta name="viewport" content="width=device-width, initial-scale=1">
```