0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JS】URLコピー機能を実装する

Posted at

概要

JSでURLコピー機能を実装する方法についてまとめる。
readonlyのinput要素から取得したURLをコピーできるようにする。

実装方法

まず、HTMLとCSSで下記を実装する。

  • 読み取り専用のinput要素
  • URLコピー用のボタン
<div class="container">
    <input id="url" type="text" value="https://example.com" readonly>
    <button id="copy">コピー</button>
</div>
.container {
    display: flex;
    gap: 8px;
    align-items: center;
}

input {
    width: 280px;
    padding: 6px;
}

次に、JSでURLコピー機能を実装する。

document.getElementById('copy').addEventListener('click', function () {
  const url = document.getElementById('url').value;

  navigator.clipboard.writeText(url)
    .then(() => {
      alert('コピーしました!');
    })
    .catch((err) => {
      console.error('コピー失敗:', err);
    });
});

ちなみに、jQueryで書くとこんな感じ。

$('#copy').on('click', function() {
	const url = $('#url').val();
	
	navigator.clipboard.writeText(url).then(() => {
		alert('コピーしました!');
	}).catch((err) => {
		console.error('コピー失敗:', err)
	});
});

Clipboard API

今回のコピー機能実装には、Clipboard APIを使用した。
Clipboard APIとはクリップボード操作用のWeb APIであり、ブラウザが提供するもの。

navigator.clipboard:Clipboard API(Web標準 API)
writeText():Clipboard APIのメソッドの1つ

まとめ

URLコピー機能はJSで実装できる。
バックエンド処理を追加する場合にも、動的URLの生成に使える。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?