MDN Web Docs

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.

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>
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

Yes No

Learn how to contribute

This page was last modified on by MDN contributors.

Read the original on developer.mozilla.org ↗