자바스크립트/DOM 예제
버튼 클릭시 클립보드에 복사하는 방법
Socratone
2021. 5. 1. 16:23
버튼을 클릭 했을 때 특정 글자를 클립보드로 복사하기 위해서는
먼저 복사하려는 글자가 담긴 엘리먼트를 불러와
엘리먼트의 textContent에 담긴 글자를 변수에 넣고
const text = document.getElementById('text').textContent;
<input>류에서만 작동하는 select 메서드를 사용하기 위해
임시로 <textarea> 엘리먼트를 만들어 textarea의 textContent에 글자를 넣는다.
const textarea = document.createElement('textarea');
textarea.textContent = text;
브라우저에 생성해야 select 메서드를 쓸 수 있으니 body에 append(추가)하고
document.body.append(textarea);
생성한 textarea를 select 메서드로 선택한 다음에 클립보드에 copy한다.
textarea.select();
document.execCommand('copy');
그리고는 곧바로 body에 append 했던 textarea를 지운다.
textarea.remove();
전체 코드는 아래와 같다.
<p id="text">글자</p>
<button id="button">복사</button>
function copyClipboard() {
const text = document.getElementById('text').textContent;
const textarea = document.createElement('textarea');
textarea.textContent = text;
document.body.append(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
}
const button = document.getElementById('button');
button.addEventListener('click', copyClipboard);