DEV Community

Cover image for How to save a string to clipboard in JavaScript
David Bilson
David Bilson

Posted on • Originally published at Medium

How to save a string to clipboard in JavaScript

There are a few methods that can be used to copy a string to clipboard in JavaScript. It is important to know how to save/copy a string to clipboard when building websites and web-based applications.

To simply save a string to clipboard, you have to ensure navigator - navigator.clipboard and navigator.clipboard.writeText are used correctly.

Clipboard.writeText() allows you to copy the string value directly to clipboard. We will see how this works shortly.


Let’s take for example;

You create a string and store it as a variable…

let stringText = “This is the text to be copied to clipboard”;
Enter fullscreen mode Exit fullscreen mode

After creating the string and storing it as a variable, you have to create a function that lets you copy the string to clipboard.

let stringText = 'I am a text copied to clipboard';

function copyBtn() {

navigator.clipboard.writeText(stringText);

}
Enter fullscreen mode Exit fullscreen mode

If the function copyBtn() is assigned to an onClick event in an html element, when clicked on, the value of the string will immediately be copied to clipboard.

Let’s create an example with a html button which would have a click event that would enable you copy the string to clipboard which you can then paste anywhere.

Remember to pass the copyBtn() function to the click event.

First create a text area in your HTML that you can paste the string to.

<textarea name='textarea' placeholder='paste your link here' cols='30' rows='5'></textarea>

Create a button below the textarea

<button onclick='copyBtn()'>Click here to copy text to clipboard</button>

Open the html file in your browser, then click on the button. The string stored in the stringText variable will be copied to clipboard, you can then paste it within the textarea.

Okay, now you are thinking "Can't I make everything happen within HTML?"... Of course you can. How? You can create a paragraph and store its textContent as variable. The copyBtn function can then fetch the variable and store the textContent of the paragraph in the clipBoard. Go ahead and give it a try.

Make sure your JavaScript file is linked to your HTML file unless you are writing JS in HTML then the JavaScript codes should go within the tag.</p> <p>I hope you found this article useful. You can check other articles I have written on JavaScript and some of the best practices. </p> <p>If there are other ways that a string can be copied to clipboard, kindly state them in the comment section.</p>

Top comments (0)