Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Last active December 23, 2020 09:32
Show Gist options
  • Select an option

  • Save manabuyasuda/c5ceb0de883a06a1e2a671b46abe7354 to your computer and use it in GitHub Desktop.

Select an option

Save manabuyasuda/c5ceb0de883a06a1e2a671b46abe7354 to your computer and use it in GitHub Desktop.
import { saveToClipboard } from './utils/saveToClipboard'
const keyword = document.getElementById('keyword')
document.getElementById('copyButton').addEventListener('click', (e) => {
saveToClipboard(keyword)
e.target.classList.add('-tooltip')
setTimeout(() => {
e.target.classList.remove('-tooltip')
}, 1000)
})
@keyframes fade-tooltip {
to {
opacity: 0;
}
}
[id="copyButton"] {
position: relative;
&.-tooltip::after {
position: absolute;
bottom: rem(-6 - 6);
left: 50%;
display: inline-block;
padding: em(6, 12) em(10, 12);
font-size: rem(12);
line-height: 1;
color: #fff;
white-space: nowrap;
content: "コピーしました";
background: #555;
border-radius: em(6, 12);
transform: translate(-50%, 0);
animation-name: fade-tooltip;
animation-duration: 2s;
animation-timing-function: ease;
animation-delay: 1s;
animation-fill-mode: forwards;
}
}
#keyword キーワード
button#copyButton(data-clipboard-target="#keyword" type="button") キーワードをコピー
/**
* クリップボードに任意の要素のテキストを保存します。
* @param {HTMLElement} target コピーするテキストを持つ要素
* @param {function} [afterCopy = false] コピー完了後のコールバック関数
* @example
* const copyButton = document.getElementById('copyButton')
* const copyButtonText = document.getElementById('copyButtonText')
* copyButton.addEventListener('click', () => {
* saveToClipboard(copyButtonText, () => {
* console.log('コピーしました。')
* })
* })
*/
const saveToClipboard = (target, afterCopy = false) => {
const tagName = target.tagName
const isEditableElement = !!(tagName === 'INPUT' || tagName === 'TEXTAREA')
if (isEditableElement) {
target.select()
}
if (!isEditableElement) {
document.getSelection().selectAllChildren(target)
}
document.execCommand('copy')
document.getSelection().empty(target)
if (afterCopy) afterCopy()
}
export { saveToClipboard }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment