onpaste

The onpaste event in HTML is triggered when content is pasted into an element, enabling developers to manage or validate the pasted information.

onpaste Event

The onpaste event attribute in HTML triggers a specified action when content is pasted into an element. It is commonly used for processing and validating pasted data in input fields.

Syntax

In HTML

index.html
<element onpaste="myScript">

In JS

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

In JavaScript, the addEventListener() function is used.

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

Example

Here’s an example demonstrating the onpaste event in HTML:

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

<input type="text" onpaste="myFunction()" value="Paste something here" size="40">

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

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

</body>
</html>

Values

  • <script>
    • Specifies the function to execute when the event occurs.
While the onpaste attribute is supported across all HTML elements, pasting content into a <p> tag requires the contenteditable attribute to be set to true.
  • In this example, when a user pastes text into the <textarea>, the handlePaste function is triggered to retrieve and process the pasted content.
The onpaste attribute is frequently used with <input> elements with type="text".

Conclusion

The onpaste event enables developers to execute actions when users paste content into an element, often used for validation or data processing. It is particularly useful for <input> and <textarea> elements. To allow pasting in elements like <p>, ensure contenteditable="true" is set.