The HTML onpaste attribute is an event handler that triggers a script to execute when the user pastes content into an element.
Definition and Usage
➔ It is often used in input fields like <input type="text"> and <textarea>.
➔ For elements that are not input fields (e.g., <div>, <p>), the onpaste event will only be triggered if the contenteditable attribute is set to "true"
➔ The onpaste event can occur in several ways, such as:
- Selecting "Paste" from the browser's Edit menu.
- Keyboard shortcuts (e.g., Ctrl + V or Cmd + V).
- Open the context menu by right-clicking and select the "Paste" command.
Syntax
//In HTML
<textarea id="ta" onpaste="myFunction()" rows="4" cols="50"></textarea>
//In javascript
object.onpaste = function() {myFunction()};
// Or using addEventListener
object.addEventListener("paste", myFunction);
Applies to
This attribute can be used on the following element.
| Attribute | Element |
|---|---|
| onpaste | All visible elements |
Example
<html>
<head>
<title>HTML onpaste attribute example</title>
</head>
<body>
<h3>HTML onpaste attribute example</h3>
<p>Copy some text and paste it into the box below.</p>
<textarea id="ta" onpaste="myFunction()" rows="4" cols="50" placeholder="Paste something here"></textarea>
<script>
function myFunction() {
document.getElementById("ta").style.border = "2px dashed blue";
document.getElementById("ta").rows = "6";
document.getElementById("ta").cols = "60";
alert("Content pasted!");
}
</script>
</body>
</html>
Click on the "copy" button and try this example in your project.