LoginSignup
17
7

More than 3 years have passed since last update.

【JavaScript】URLをコピーするボタンを作る

Posted at

概要

URLをコピーするボタンをJavaScriptで実装する。
実装はとっても簡単なのでサクッと書きます。

実装(html)

<button onclick="copyUrl()">Copy URL</button>

実装(JavaScript)

function copyUrl() {
    const element = document.createElement('input');
    element.value = location.href;
    document.body.appendChild(element);
    element.select();
    document.execCommand('copy');
    document.body.removeChild(element);
}

URLをコピーするにはテキストボックスを用意し、そこにURL(location.href)を設定します。
テキストボックスをDOMに追加した後、 select() で設定したURLを選択した状態にします。

document.execCommand('copy') でコピーを実行したら用意したテキストボックスを削除します。

以上、簡単ですね。

17
7
0

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
17
7