Question: I spent a good 20 min searching online for this, but couldn't find it. What I want is to to be able to copy a text string on click *without a button*. The text string will be inside a "span" class.

1. User hovers over text string
2. User clicks text string
3. Text string is copied to clipboard

Any help would be greatly appreciated. Thanks!

Answer: 
Use the Clipboard API!
======================

The simplest modern solution is:

```
navigator.clipboard.writeText(value)

```

That value can later be accessed with:

```
navigator.clipboard.readText()

```

> 
> *NOTE*: To use in an **`iframe`**, you'll need to add write (and maybe read) permissions
> 
> 
> 
> ```
> <iframe src='' allow='clipboard-read; clipboard-write'/>
> 
> ```
> 
> 

> 
> *NOTE*: To use in an browser extension (on a webpage), you'll need either to:
> 
> 
> * call from a user triggered event (`click`...)
> * add the '`clipboardWrite`' permission to the manifest
> 
> 
> 

> 
> *NOTE*: To use in the dev console, use `copy()` instead
> 
> 
> 
> ```
> copy('string')
> 
> ```
> 
> 

[W3Schools Tutorial](https://www.w3schools.com/howto/howto_js_copy_clipboard.asp)

[CanIUse](https://caniuse.com/mdn-api_clipboard_writetext)
HTML: 

```
<button type='button' id='btn'>Copy</button>

```

JS

```js
document.querySelect('#btn').addEventListener('click', function() {
   copyToClipboard('copy this text');
});

```

JS / Function:

```js
function copyToClipboard(text) {
    var selected = false;
    var el = document.createElement('textarea');
    el.value = text;
    el.setAttribute('readonly', '');
    el.style.position = 'absolute';
    el.style.left = '-9999px';
    document.body.appendChild(el);
    if (document.getSelection().rangeCount > 0) {
        selected = document.getSelection().getRangeAt(0)
    }
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
    }
};

```