Copy active page URL button

Want to give your audience a quick way to copy the current page's URL to the clipboard so they can share it easily? Use this tutorial to help!

I use a code block in an Oxygen post template, but you can achieve cool button using pretty much any standard web development tool. The final result should look something like this:

The button (HTML)

<button class="copy-url-btn" onclick="copyUrl()">
  <span class="copy-url-btn-tooltip">Copy link</span>
  <svg
    viewBox="0 0 24 24"
    height="24px"
    width="24px"
    xmlns="http://www.w3.org/2000/svg"
  >
    <title />
    <path d="M7,17A5,5,0,0,1,7,7h3a5,5,0,0,1,5,5,1,1,0,0,1-2,0,3,3,0,0,0-3-3H7a3,3,0,0,0,0,6,1,1,0,0,1,0,2Z"
      fill="#000"
    />
    <path d="M17,17H14a5,5,0,0,1-5-5,1,1,0,0,1,2,0,3,3,0,0,0,3,3h3a3,3,0,0,0,0-6,1,1,0,0,1,0-2,5,5,0,0,1,0,10Z"
      fill="#000"
    />
  </svg>
</button>

Button and tooltip stylings (CSS)

.copy-url-btn {
  background: none;
  border: none;
  border-radius: 0;
  padding: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.copy-url-btn.pulse {
  animation: pulse 300ms forwards ease-in-out;
  position: relative;
}

@-webkit-keyframes pulse {
  0% {
    top: 0px;
  }
  50% {
    top: -5px;
  }
  100% {
    top: 0px;
  }
}

.copy-url-btn-tooltip {
  order: 2;
  display: none;
  margin-left: 10px;
  font-size: 12px;
  background-color: #000;
  color: #fff;
  padding: 6px 10px;
  border-radius: 3px;
}

Button functionality (JS)

function copyUrl() {
	if (!window.getSelection) {
		alert('Please copy the URL from the location bar.');
		return;
	}
	const dummy = document.createElement('p');
	dummy.textContent = window.location.href;
	document.body.appendChild(dummy);

	const range = document.createRange();
	range.setStartBefore(dummy);
	range.setEndAfter(dummy);

	const selection = window.getSelection();

	selection.removeAllRanges();
	selection.addRange(range);

	document.execCommand('copy');
	document.body.removeChild(dummy);

	document.querySelector('.copy-url-btn').classList.add("pulse");
	document.querySelector('.copy-url-btn-tooltip').style.display = "block";
	document.querySelector('.copy-url-btn-tooltip').innerHTML = "Copied!";
	setTimeout(function() {
		document.querySelector('.copy-url-btn').classList.remove("pulse");
		document.querySelector('.copy-url-btn-tooltip').innerHTML = "Copy link";
		document.querySelector('.copy-url-btn-tooltip').style.display = "none";
	}, 350);
}

Credit to ppajer on Stackoverflow for providing the above JS which I modified.

Let's talk.

Google reCaptcha: Invalid site key.