As a developer, we know how useful and good it is to have a “copy” button sitting next to a code block. In some cases, it helps a lot in increasing the usability of our website.

In this post, we are going to make the text copiable to the clipboard with just a few lines of JavaScript.

The markup

To make this post quick and easy to digest, I will use Tailwind CSS to style the app and make everything look nice.

So, for the HTML part, it will be very simple (except the bunch of classes added by Tailwind CSS).

<main class="flex flex-col h-screen justify-center items-center bg-gray-100">
  <div class="bg-white max-w-sm p-5 rounded shadow-md mb-3">
    <input
      class="border-blue-500 border-solid border rounded py-2 px-4"
      type="text"
      placeholder="Enter some text"
      id="copyMe"
    />
    <button
      class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 border border-blue-700 rounded"
      onclick="copyMeOnClipboard()"
    >
      Copy
    </button>
  </div>
  <p class="text-green-700"></p>
</main>

#javascript #programming

How to copy text to the clipboard with JavaScript ?
13.40 GEEK