oncopy

The oncopy event attribute in HTML triggers a function when the user copies content from an element.

oncopy Event

The oncopy event is triggered when a user copies content from an element, typically using keyboard shortcuts or the context menu. This event enables custom actions or notifications to be executed upon copying. To use it, attach the attribute to an element and define a script to run when the event occurs.

Syntax

In HTML

index.html
<element oncopy="myScript">

In JS

script.js
object.oncopy = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("copy", myScript);

Example

::event-oncopy ::
index.html
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The oncopy Event</h2>

<input type="text" oncopy="myFunction()" value="Try to copy me">

<p id="demo"></p>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "You copied text!"
}
</script>

</body>
</html>

Values

  • <script>
    • Specifies the function to execute when the event is triggered.
The oncopy attribute is commonly used with <input> elements that have type="text".

Conclusion

The oncopy event lets you define custom actions when a user copies content from an element. It is particularly useful for <input> fields with type="text". By assigning a function, you can implement features such as notifications or logging when copying occurs.