Copy to clipboard can be used to make easy for a user to copy a particular text. User will not need to select the text first and then copy it. This can be achieved with just a button click.
I'm going to explain copy to clipboard by using JavaScript/jQuery. It also execute copy command to copy the content.
Here is the code for copy to clipboard in JavaScript/jQuery. Like i have created a index HTML file.
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<!DOCTYPE html> <html> <title>Copy to clipboard example in JavaScript/jQuery</title> <head> <style> .copyMsg { width:200px; height:auto; position:fixed; z-index: 2; /* Make sure its above other items. */ top: 50%; left: 50%; margin-top: -10%; /* Changes with height. */ margin-left: -10%; /* Your width divided by 2. */ background-color: #383838; color: #F0F0F0; font-family: Calibri; font-size: 20px; padding:10px; text-align:center; border-radius: 2px; -webkit-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1); -moz-box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1); box-shadow: 0px 0px 24px -1px rgba(56, 56, 56, 1); } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript" language="javascript" > function copyToClipboard(message) { var input = document.createElement("input"); input.setAttribute("type", "text"); input.setAttribute('value',message); document.body.appendChild(input); input.select(); document.execCommand("copy"); document.body.removeChild(input); $('.copyMsg').fadeIn(400).delay(200).fadeOut(400); } $(document).on('click', '.copyMsgBtn', function(e) { var message = $('#message').text(); copyToClipboard(message); }); </script> </head> <body> <h1 id="message">Copy to clipboard example in JavaScript/jQuery</h1> <button class="copyMsgBtn"> Copy </button> <div class='copyMsg' style='display:none'>Copied!</div> </body> </html> |
When you click on copy button we get the text and pass it to copyToClipboard() function. There I created a temporary input text field and assign that message to the input text field. Then I select the input text by select() function and execute the copy command by execCommand() function. After executing the copy command I removed the temporary text field. Whenever the message is copied you will see the copied! message also. ...