Element: paste event

فهرست فصل‌ها دانلود آرشیوناشر

MDN Web Docs · نسخهٔ df622a2a1c1e · CC BY-SA 2.5 و مجوز جداگانهٔ ناشر برای نمونه‌کد

{{APIRef("Clipboard API")}}

The **paste** event of the Clipboard API is fired 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 {{HTMLElement("textarea")}} or an element with [contenteditable](/en-US/docs/Web/HTML/Reference/Global_attributes/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 {{domxref("DataTransfer/getData", "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 {{domxref("Event/preventDefault", "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.

This event bubbles up the DOM tree, eventually to {{domxref("Document")}} and {{domxref("Window")}}, is cancelable and is composed.

Syntax

Use the event name in {{domxref("EventTarget/addEventListener", "addEventListener()")}}:

js-nolint
addEventListener("paste", (event) => { })

Alternatively, assign to the event handler property of the interface:

js-nolint
onpaste = (event) => { }

Event type

A {{domxref("ClipboardEvent")}}. Inherits from {{domxref("Event")}}.

{{InheritanceDiagram("ClipboardEvent")}}

Examples

Live example

HTML

html
<div class="source" contenteditable="true">Copy text from this box.</div>
<div class="target" contenteditable="true">And paste it into this one.</div>
css hidden

JavaScript

js
const target = document.querySelector("div.target");

target.addEventListener("paste", (event) => {
  event.preventDefault();

  let paste = (event.clipboardData || window.clipboardData).getData("text");
  paste = paste.toUpperCase();
  const selection = window.getSelection();
  if (!selection.rangeCount) return;
  selection.deleteFromDocument();
  selection.getRangeAt(0).insertNode(document.createTextNode(paste));
  selection.collapseToEnd();
});

Result

{{ EmbedLiveSample('Live_example', '100%', '120px') }}

Specifications

{{Specifications}}

Browser compatibility

{{Compat}}

See also

  • {{domxref("Element/cut_event", "cut")}} event
  • {{domxref("Element/copy_event", "copy")}} event