Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Element
  4. paste

Element: paste event

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

Thepaste event of theClipboard 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<textarea> or an element withcontenteditable attribute set totrue) 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 callinggetData() on the event'sclipboardData 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 usingevent.preventDefault(), and then insert its desired data manually.

It's possible to construct and dispatch asyntheticpaste event, but this will not affect the document's contents.

This eventbubbles up the DOM tree, eventually toDocument andWindow, iscancelable and iscomposed.

Syntax

Use the event name in methods likeaddEventListener(), or set an event handler property.

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

Event type

AClipboardEvent. Inherits fromEvent.

Event ClipboardEvent

Examples

Live example

HTML

html
<div contenteditable="true">Copy text from this box.</div><div contenteditable="true">And paste it into this one.</div>
div.source,div.target {  border: 1px solid gray;  margin: 0.5rem;  padding: 0.5rem;  height: 1rem;  background-color: #e9eef1;}

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

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp