このブログはプログラミングメモブログと題していて、便利だったからまた使うかもしれないコードスニペットを書くのがメインテーマだったりするのですが、何故か今まで実装していなかった「コードをコピーするボタン」。
ちょこっとJavaScript書けばできるだろうなと思いつつやってなかったのですが、ChatGPT先生にお願いして書いてもらったものが一発で動いたのでシェア。
設定方法
設定はわりと簡単で、以下のコードをはてなブログのデザイン設定→フッターに入れるだけ。
コード
アイコンを全部絵文字でやってくれたので画像ファイルも用意しなくてOK。助かる。
コードブロック自体のシンタックスハイライトは過去記事を参考に設定ください。
<script> document.querySelectorAll("pre").forEach((pre) => { // ボタン要素を作成 const button = document.createElement("button"); button.textContent = "📋 Copy"; button.style.position = "absolute"; button.style.top = "5px"; button.style.right = "5px"; button.style.padding = "5px 10px"; button.style.fontSize = "12px"; button.style.cursor = "pointer"; button.style.border = "none"; button.style.borderRadius = "5px"; button.style.background = "rgba(0, 0, 0, 0.7)"; button.style.color = "white"; // `pre` の親要素を relative にする const wrapper = document.createElement("div"); wrapper.style.position = "relative"; pre.parentNode.insertBefore(wrapper, pre); wrapper.appendChild(pre); wrapper.appendChild(button); // コピー処理 button.addEventListener("click", async () => { const codeLines = Array.from(pre.querySelectorAll("div")) .map((div) => div.textContent) .join("\n"); try { await navigator.clipboard.writeText(codeLines); button.textContent = "✔ Copied!"; setTimeout(() => (button.textContent = "📋 Copy"), 1500); } catch (err) { console.error("Copy failed", err); button.textContent = "❌ Error"; setTimeout(() => (button.textContent = "📋 Copy"), 1500); } }); }); </script>