Copy text to the clipboard with javascript!

When I started building this website I wanted the titles of the blog pages to be clickable. When you click on it the page url will be copied to the clipboard. This is a handy feature and for anyone who is also looking for this functionality, this is how i have done it.

In your javascript create a textarea element. Then assign the string you want to copy to the clipboard as the value of the textarea.

When the element has a value it should be appended to the dom. The select the text inside this newly appended textarea.

Then the copy command can be executed. When the text is copied the textarea can be removed from the dom and your text should be available to paste.

To throw this all together you can use this as a function.

const saveToClipboard = str => {
  const element = document.createElement('textarea');
  element.value = str;
A snippet from a post template

Check out the pen below to see this in action.

Hello! šŸ‘‹