Click To Select And Copy Text In JavaScript

Here is a script that can be used for referral codes or anything that you want to allow users to easily copy.

<div>
  <p>
    <input class="js-referral-url" type="text" readonly="readonly" value="https://www.hashbangcode.com/" />
  </p>

  <p>Click on the text box to select and copy the text.</p>
</div>

The JavaScript uses the class of the input element and adds two event listeners to it to that the element is selected and the content copied.

window.onload = function () {
  const shareUrl = document.querySelector(".js-referral-url");

  const copyContent = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl.value);
    } catch (err) {
      /* empty */
    }
  };

  if (shareUrl) {
    shareUrl.addEventListener("focus", () => shareUrl.select());
    shareUrl.addEventListener("click", copyContent, false);
  }
};

Use the following CSS to give the input element some extra style.

div {
  width: 50%;  
}

.js-referral-url{
  cursor: pointer;
  width: 100%;
  font-size: 20px;
}

See this script in action on codepen.

Add new comment

The content of this field is kept private and will not be shown publicly.