References

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

The HTML oncopy event

Event All modern browsers Updated
Quick answer

The HTML oncopy attribute runs JavaScript when the user copies the element's content to the clipboard. It is an inline handler for the copy event; in modern code prefer addEventListener('copy', …).

Overview

The oncopy event attribute runs JavaScript when content is copied. In JavaScript the event itself is named copy — 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 oncopy HTML attribute, but the modern, recommended approach is element.addEventListener('copy', 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 oncopy="handler()">…</element>

element.addEventListener('copy', handler);

Example

Live example
<p oncopy="this.nextElementSibling.textContent='Copied!'">Select and copy this text.</p><span></span>

Best practices

  • Prefer element.addEventListener('copy', handler) over the inline oncopy 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 oncopy event?
It runs JavaScript when content is copied. In JavaScript the event is named copy.
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 oncopy attribute or addEventListener?
Prefer addEventListener('copy', …) in JavaScript. The inline oncopy attribute works but mixes behavior into the markup and allows only one handler per element.