Kimama-IT

ITに関する覚書き

【HTML】【JavaScript】クリックした文字列をクリップボードにコピーする。#1

ページ内のリンクをクリックしたときに、リンクの文字をクリップボードにコピーする方法を記載します。

全構文

<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>テストページ</title>
    <!-- 以下、CSSを記載する。 -->
    <style type="text/css">
      #notification {
        background-color: powderblue;
      }
      #notification.invisible {
        opacity: 0;
      }
      #notification.visible {
        opacity: 1;
      }
    </style>
  </head>
  <body>
    <p id="notification" class="invisible">をクリップボードにコピーしました。</p>
    <p>以下のリンクをクリックして、対象の文字をクリップボードにコピーする。</p>

    <!-- 以下、tableを作成する。  -->
    <table border="1">
      <tr>
        <th>No</th>
        <th>ことわざ</th>
      </tr>
      <tr>
        <td></td>
        <td><a href="javascript:void(0)">井の中の蛙大海を知らず</a></td>
      </tr>
      <tr>
        <td></td>
        <td><a href="javascript:void(0)">海老で鯛を釣る</a></td>
      </tr>
      <tr>
        <td></td>
        <td><a href="javascript:void(0)">急がば回れ</a></td>
      </tr>
    </table>

    <!-- 以下、javascriptを記載。bodyタグ内の下部に以下を入力する。  -->
    <script language="javascript" type="text/javascript">

      // tableタグを持つ要素の子孫のaタグを持つ複数要素を取得する。
      const aElem = document.querySelectorAll("table a");
      // notificationのid属性を持つ要素を取得する。
      const notiElem = document.querySelector("#notification");
      let timeoutID = undefined;

      // aElemの中からひとつずつ要素を取り出して、EventListenerに追加する。
      // 追加したEventListenerにより、aタグの文字列がクリックされたときに指定の関数が実行される。
      aElem.forEach(function(value) {
        value.addEventListener("click", updateClipboard);
      });

      // クリップボードに文字列をコピーする。
      function updateClipboard(event) {
        navigator.clipboard.writeText(event.srcElement.innerText).then(() => {
          // コピーに成功したときの処理をここに記載する。
          // 現在タイムアウト処理中であれば、タイムアウト処理を中止する
          if (typeof timeoutID === 'number') {
            notificationClearTimeout();
          }
          // 通知の内容をコピーした文字列に差し替える。
          notiElem.innerHTML = event.srcElement.innerText + " をクリップボードにコピーしました。";
          notificationActive();
        }, () => {
          // コピーに失敗したときの処理をここに記載する。
          alert("コピー失敗");
        });
      }

      // 通知を表示する。
      function notificationActive() {
        // notiElemのinvisibleクラスをvisibleクラスに置き換える。
        notiElem.classList.replace("invisible","visible");
        // タイムアウト処理を開始する、そのタイムアウト処理の識別子が返値となる。
        timeoutID = setTimeout(() => {
          // 指定のミリ秒後にnotiElemからvisibleクラスをinvisibleクラスに置き換える。
          notiElem.classList.replace("visible","invisible");
        }, 1200);
      }

      // タイムアウト処理を中止する。
      function notificationClearTimeout() {
        clearTimeout(timeoutID);
      }

    </script>
  </body>
</html>