
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Secretly Copy to Clipboard using JavaScript in Chrome and Firefox
In this article we are going to try how to secretly copy a JavaScript function to the clipboard.
We use the copytext() method to secretly copy JavaScript function to the clipboard. These functions work on JavaScript console as well. To understand better let's look into the examples one by one.
Example
Following is the example program we used copyText() method to copy text to clipboard using JavaScript function.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <input type="text" value="Copy me!" id="myInput"> <button onclick="copyText()">Copy text</button> <script> function copyText() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); // alert("Copied the text: " + copyText.value); } </script> </body> </html>
Adding an alert
We can also add an alert, using the alert() method, to the text copied by the copytext() method.
Example
Following is the example program to copy text to clipboard and an alert will be displayed after copying the text.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <input type="text" value="Copy me!" id="myInput"> <button onclick="copyText()">Copy text</button> <script> function copyText() { var copyText = document.getElementById("myInput"); copyText.select(); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } </script> </body> </html>
Alert for the copied text reads ?
Example
Following is the example program to copy text to clipboard using copyClipboard() function ?
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <input type="text" value="Text" id="input"> <button onclick="copyClipboard()">Copy text Here!</button> <script> function copyClipboard() { var sampleText = document.getElementById("input"); sampleText.select(); sampleText.setSelectionRange(0, 99999) document.execCommand("copy"); alert("Copied the text: " + sampleText.value); document.write("Copied Text here:", sampleText.value); } </script> </body> </html>
Advertisements