Copy Textarea Content Using Native JavaScript
To copy the textarea content using native JavasScript you can simply select the textarea using "select()" function and then execute the "copy" command. For the HTML code, it's as simple as the following.
<textarea>Hello world</textarea> <button> Copy </button>
<script> document.querySelector("button").onclick = function(){ document.querySelector("textarea").select(); document.execCommand('copy'); } </script>
Copy Textarea Content With jQuery
Using jQuery is also really handy, you can have the same HTML markup as above, and then for the on "click" you just attach the code like you normally would.
<script> $("button").click(function(){ $("textarea").select(); document.execCommand('copy'); }); </script>
Copy Textarea Content With AlpineJS
For Alpine JS you can have the textarea with a custom reference and then when the button is clicked you perform the "copy" command.
<div x-data="copyme"> <textarea x-ref="textarea">Hello world</textarea> <button @click="copyTextarea"> Copy </button> </div>
<script> document.addEventListener('alpine:init', () => { Alpine.data('dropdown', () => ({ copyTextarea() { this.$refs.textarea.select(); document.execCommand('copy'); } })); }); </script>
Leave a reply