Copy Current Page URL Button
Copies the current page URL to the clipboard when any element with a data-copy-url attribute is clicked, with a brief visual confirmation.
JavaScriptby SnipCraft
js
(function () {
'use strict';
document.addEventListener('DOMContentLoaded', function () {
var buttons = document.querySelectorAll('[data-copy-url]');
if (!buttons.length) { return; }
function fallbackCopy(text, btn) {
var ta = document.createElement('textarea');
ta.value = text;
ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0;';
document.body.appendChild(ta);
ta.focus();
ta.select();
try { document.execCommand('copy'); } catch (err) { /* unsupported */ }
document.body.removeChild(ta);
showFeedback(btn);
}
function showFeedback(btn) {
var original = btn.textContent;
btn.textContent = btn.getAttribute('data-copied-label') || 'Copied!';
btn.setAttribute('disabled', 'disabled');
setTimeout(function () {
btn.textContent = original;
btn.removeAttribute('disabled');
}, 2000);
}
buttons.forEach(function (btn) {
btn.addEventListener('click', function (e) {
e.preventDefault();
var url = window.location.href;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url)
.then(function () { showFeedback(btn); })
.catch(function () { fallbackCopy(url, btn); });
} else {
fallbackCopy(url, btn);
}
});
});
});
}());#button#clipboard#sharing#url#ux