Skip to content

Commit

Permalink
Add target option (#34)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
Haraldson and sindresorhus committed Apr 6, 2020
1 parent 7ee4cd9 commit c32271e
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
28 changes: 27 additions & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,29 @@
/// <reference lib="dom"/>

declare namespace copyTextToClipboard {
interface Options {
/**
Specify a DOM element where the temporary, behind-the-scenes `textarea` should be appended, in cases where you need to stay within a focus trap, like in a modal.
@default document.body
@example
```
import copy = require('copy-text-to-clipboard');
const modalWithFocusTrap = document.getElementById('modal');
button.addEventListener('click', () => {
copy('🦄🌈', {
target: modalWithFocusTrap
});
});
```
*/
target?: HTMLElement;
}
}

declare const copyTextToClipboard: {
/**
Copy text to the clipboard.
Expand All @@ -16,7 +42,7 @@ declare const copyTextToClipboard: {
});
```
*/
(text: string): boolean;
(text: string, options?: copyTextToClipboard.Options): boolean;

// TODO: Remove this for the next major release, refactor the whole definition to:
// declare function copyTextToClipboard(text: string): boolean;
Expand Down
4 changes: 2 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const copyTextToClipboard = input => {
const copyTextToClipboard = (input, {target = document.body} = {}) => {
const element = document.createElement('textarea');
const previouslyFocusedElement = document.activeElement;

Expand All @@ -20,7 +20,7 @@ const copyTextToClipboard = input => {
originalRange = selection.getRangeAt(0);
}

document.body.append(element);
target.append(element);
element.select();

// Explicit selection workaround for iOS
Expand Down
12 changes: 11 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,24 @@ button.addEventListener('click', () => {

## API

### copy(text)
### copy(text, options?)

Copy `text` to the clipboard.

Returns a `boolean` of whether it succeeded to copy the text.

Must be called in response to a user gesture event, like `click` or `keyup`.

#### options

Type: `object`

##### target

Type: `HTMLElement`\
Default: `document.body`

Specify a DOM element where the temporary, behind-the-scenes `textarea` should be appended, in cases where you need to stay within a focus trap, like in a modal.

## Related

Expand Down

0 comments on commit c32271e

Please sign in to comment.