References

Beginner-friendly references for web development, with live, editable examples.

The HTML onpaste event

Event All modern browsers Updated
Quick answer

The HTML onpaste attribute runs JavaScript when the user pastes content into the element. It is an inline handler for the paste event; in modern code prefer addEventListener('paste', …).

Overview

The onpaste event attribute runs JavaScript when content is pasted. In JavaScript the event itself is named paste. Drop the on prefix when you call addEventListener.

It is a clipboard event. The handler receives a ClipboardEvent whose clipboardData object lets you read what is being pasted (it is read-only during paste), for example to inspect and sanitize content before inserting it yourself.

You can wire this up with the inline onpaste HTML attribute, but the modern, recommended approach is element.addEventListener('paste', handler) in JavaScript. That keeps behavior out of your markup, lets you attach several handlers to the same event, and makes them easy to remove. The inline attribute is fine for quick demos.

Syntax

<element onpaste="handler()"></element>

element.addEventListener('paste', handler);

Example

Live example
<input onpaste="this.nextElementSibling.textContent='Pasted!'" placeholder="Paste here" style="padding:8px;"><span></span>

Best practices

  • Prefer element.addEventListener('paste', handler) over the inline onpaste attribute; it separates behavior from markup and allows multiple handlers.
  • Call event.preventDefault() before writing your own data to clipboardData.
  • Sanitize pasted content rather than trusting it as-is.
  • Do not block normal copy/paste; interfering with it frustrates users.

Frequently asked questions

What is the onpaste event?
It runs JavaScript when content is pasted. In JavaScript the event is named paste.
How do I access the pasted data?
Read it with event.clipboardData.getData('text/plain'). During paste the clipboard data is read-only, so you cannot write to it.
Can I change what gets pasted?
Yes, but not by writing to clipboardData, which is read-only during paste. Call preventDefault(), read the text with event.clipboardData.getData('text/plain'), sanitize it, and insert it yourself.
Should I use the onpaste attribute or addEventListener?
Prefer element.addEventListener('paste', …) in JavaScript. The inline onpaste attribute works but mixes behavior into the markup and allows only one handler per element.