Using HTML and JavaScript, Copy Text To The Clipboard

Hello guys, today I’m going to show you how we can copy text from the HTML element programmatically. For this, we are going to use simple Javascript
code.

We have two ways to achieve this task.

Old School

The conventional procedure is to establish a text area, enter the text to be copied there, and then call the document. To copy the text to the clipboard, use the execCommand command to perform the copy command.

For instance, we might write:

const text = 'hello world'
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";

document.body.appendChild(textArea);
textArea.focus();
textArea.select();

try {
  const successful = document.execCommand('copy');
  const msg = successful ? 'successful' : 'unsuccessful';
  console.log(msg);
} catch (err) {
  console.error(err);
}

document.body.removeChild(textArea);

The text that we wish to copy to the clipboard is included in the text variable.

The document is then produced. To construct a textarea element, use the createElement method.

The text is then entered into the text area after setting the textArea’s value to the text.

To avoid scrolling to the bottom, the top, left, and position styles are then specified.

Next, document.body is called. To add the text area to the body, use appendChild with textArea.

Next, we concentrate on the textArea under scrutiny.

The text in the text field is then selected using the select command so that we may copy it.

The copy command is then issued by using document.execCommand with the argument ‘copy’ to copy the text that has been chosen in the text field.

A boolean is returned to show if the command was executed correctly.

The text may then be pasted anywhere we choose.

The New Way

The new JavaScript method for programmatically copying text to the clipboard is much cleaner.

Just the navigator, please. clipboard. To programmatically copy the text to the clipboard, use the writeText method with the text that needs to be copied as the parameter.

We put this in writing:

const text = "abc";
(async () => {
  await navigator.clipboard.writeText(text);
})();

To copy the text, we just use navigator.clipboard.writeText while passing text.

In order for us to use it in an async function, it returns a promise with the copy status.

More recent browsers support these.

So, these are known ways that can be used to copy HTML text into a clipboard.

I hope you will like it.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories