0
0

More than 1 year has passed since last update.

JavaScriptでコピーボタンを実装する方法

Last updated at Posted at 2021-10-06

はじめに

JavaScriptを使ってコピーボタンを作る方法を知ったので、書いていく。
少し衝撃的だった

手順

  1. textareaタグを生成する
  2. textaretaタグの中にコピーしたい文言を入れ込む
  3. bodyタグを取得してappendChildでtextareaを入れ込む
  4. select()で選択状態にする
  5. execCommand('copy')でコピー
  6. textareaを消す

コードの例

const textarea = document.createElement('textarea')
textarea.textContent = password

const body = document.querySelector('body')
body.appendChild(textarea)
textarea .select()
document.execCommand('copy')
body.removeChild(textarea);
alert('copied password')

ポイント

上記のコードでは変数passwordにコピーしたい文言が格納されていることを想定しています。
textareaタグを作って格納されている値をコピーして消去する。
これを一瞬で行っているわけですね。

おわりに

一見複雑に見えて慣れてしまえば簡単ですね。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0