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

HTMLWeb DevelopmentFront End Technology

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…

Example

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>

Output

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>

Output

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".

raja
Updated on 05-Sep-2022 13:16:47

Advertisements