Execute a script when the content of the element is being copied in HTML?

When a user copies the content of an element, the oncopy event takes place.When a user copies an element, such as an image made using the<img> element, the oncopy event also takes place.The <input> elements with type="text" are the ones that often use the oncopy event.

Following are the examples…


In the following example we are running a javascript when copying text of an <input> element.

<!DOCTYPE html> <html> <body> <input type="text" oncopy="myFunction()" value="Welcome to tutorialspoint"> <p id="tutorial"></p> <script> function myFunction() { document.getElementById("tutorial").innerHTML = "Text is copied!" } </script> </body> </html>


When the script gets executed , the window will pop up with the text "welcome to tutorialspoint" and when we try to copy text, it will display "text is copied".

Example: (using the addEventListener())

In the following example we are using addeventlistener() method to know when our text got copied.

<!DOCTYPE html> <html> <body> <input type="text" id="tutorial" value="The Best E-Way"> <script> document.getElementById("tutorial").addEventListener("copy", mytutorial1); function mytutorial1() { alert("Text Get Copied !"); } </script> </body> </html>


On executing the above script , it will display a text "the best e-way" and when we try to copy the text, it will create an alert saying "text got copied".

Updated on: 05-Sep-2022


Kickstart Your Career

Get certified by completing the course

Get Started