Copy text in Javascript
To copy the text in javascript we can use execCommand(“copy”). This command copies the selected text. Check latest magento 2 extensions.
To copy the text in javascript we can use execCommand(“copy”). This command copies the selected text.
Here is an example that I used to copy the browser URL.
<input type="button" onclick="copyOnClick()" value="Copy" />
function copyOnClick() { var tempInput = document.createElement("input"); tempInput.style = "position: absolute; left: -1000px; top: -1000px"; tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); document.execCommand("copy"); document.body.removeChild(tempInput); alert("Link copied"); }
Now on button click, the javascript function copyOnClick() will execute because copyOnClick() is written in the ‘onclick’ event.
As you can see in the code a temporary input field has the browser URL as its value. With the select() command the text value of the temporary input field is selected and the execCommand(“copy”) copies it.
At last, remove the temporary created input.
Happy coding 🙂
2 comments