Semanticize intermediate headings
This commit is contained in:
@ -7,7 +7,7 @@ cover: blog_images/copy-text-to-clipboard-with-javascript.jpg
|
||||
excerpt: Learn how to programmatically copy text to clipboard with a few lines of JavaScript and level up your web development skills.
|
||||
---
|
||||
|
||||
**Core functionality**
|
||||
### Core functionality
|
||||
|
||||
A very common need when building websites is the ability to copy text to clipboard with a single button click. Javascript can easily do this in five short steps:hout the user selecting it or hitting the appropriate key combination on their keyboard. Javascript can easily do this in five short steps:
|
||||
|
||||
@ -32,7 +32,7 @@ const copyToClipboard = str => {
|
||||
|
||||
Bear in mind that this method will not work everywhere, but only as a result of a user action (e.g. inside a `click` event listener), due to the way `Document.execCommand()` works.
|
||||
|
||||
**Hide the appended element**
|
||||
### Hide the appended element
|
||||
|
||||
The above method, while functional, might have some issues such as flashing when appending and removing the `<textarea>`, a problem that is even more apparent when considering accessibility. A major improvement to this method comes from adding some CSS to make the element invisible and restrict editing by users:
|
||||
|
||||
@ -50,7 +50,7 @@ const copyToClipboard = str => {
|
||||
};
|
||||
```
|
||||
|
||||
**Save and restore the original document's selection**
|
||||
### Save and restore the original document's selection
|
||||
|
||||
The final consideration before wrapping this up is respecting the user's previous interaction with the website, like having already selected some content. Luckily, we can now use some modern Javascript methods and properties like `DocumentOrShadowRoot.getSelection()`, `Selection.rangeCount`, `Selection.getRangeAt()`, `Selection.removeAllRanges()` and `Selection.addRange()` to save and restore the original document selection. You can find the final code with these improvements implemented in the [copyToClipboard snippet](/js/s/copy-to-clipboard/).
|
||||
|
||||
|
||||
Reference in New Issue
Block a user