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 or modify what is being transferred — for example to sanitize pasted content or add a copyright line to copied text.

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 copied or pasted data?
Read or set it via event.clipboardData on the ClipboardEvent.
Can I modify what gets copied?
Yes — call preventDefault() and write your own value to event.clipboardData.
Should I use the onpaste attribute or addEventListener?
Prefer addEventListener('paste', …) in JavaScript. The inline onpaste attribute works but mixes behavior into the markup and allows only one handler per element.