Member-only story
How to Copy a String into Clipboard in JavaScript
Below is the Javascript code on how to copy a string into a clipboard in Javascript.
function myFunction() {
// variable content to be copied
var copyText = "Test"
// create an input element
let input = document.createElement('input');
// setting it's type to be text
input.setAttribute('type', 'text');
// setting the input value to equal to the text we are copying
input.value = copyText;
// appending it to the document
document.body.appendChild(input);
// calling the select, to select the text displayed
// if it's not in the document we won't be able to
input.select();
// calling the copy command
document.execCommand("copy");
// removing the input from the document
document.body.removeChild(input)
}
Below is the HTML code.
<button onclick="myFunction()">Copy text</button>
Click here to run the code snippet.
Amazon Links to “Must-Haves” as a WFH Software Engineer 🙂💻
24-inch budget-friendly monitor, Portable monitor, Laptop stand, Waterproof desk mat, Keyboard cleaning gel, Six-outlet wall charger and surge protector,, Wi-Fi extender, Blue-light–blocking glasses, Memory foam gel pad, Foam footrest
Courses to learn more about datastructures/algorithms ✍️
Courses to learn more about databases 👓
DB Foundations, Data Scientists specialization
Courses to learn more about React 🧢
Full-Stack WebDev, Front-End WebDev with React, IBM Full Stack