Hajime, the duck guy

Forms kata
On this page
Level: Important

Copy text to clipboard

Implement a button that copies some text to clipboard

The way of kata

Kata is an exercise for muscle memory. It's not intended to fill your brain with information but train your fingers to react. The information is there to give you the why, but your fingers need to learn the how.

The material on this page is presented in a specific order — from least specific to highly technical. You will learn the most by jumping in as soon as you have some idea of what you should do. Once you're done, read the rest of the material and check your solution.

All katas are designed to be doable without using 3rd party libraries (and, in fact, the point is to also learn how to do what these libraries do).

To make the best of katas, observe the following rules.

  • Don't rush.
  • When stuck, take a break and do something unrelated.
  • Do not copy/paste code. Always retype everything.
  • Do not use AI tools to generate code.
  • Try to do something that wasn't in the instructions, experiment.
  • Repeat the kata from time to time, even if you think you've got it.
  • You have mastered the kata once you are able to complete it without thinking too much.

Remember, the goal is not to get it done, but to get some practice.

Introduction

In this exercise you will practice working with the browser's clipboard.

Skills you will acquire

  • Basic feature detection
  • Clipboard API

Objective

  • Display a button that copies to clipboard when clipboard is available
  • Copy the contents of an input to clipboard

Check your solution

  • A read-only input is shown
  • The value of the input is set after the page loads
  • When clipboard is available a button is shown
  • Clicking the button will copy the contents of the input into the clipboard

Keep in mind

Although the clipboard API is available in most modern browser, we will assume that it might not be available for some of the users. As a fallback, you can use a simple read-only input to hold the copyable text, as users can then focus the input and copy it manually.

To mimic a real-life use case, set the input text using JavaScript after the page loads.

The button to copy the text to clipboard should not be shown by default. In general, we want to avoid showing unusable controls. The button should be presented only once we know the clipboard API can be used. The usual way to test for features is to determine that the objects and/or functions are present in the global namespace. For example, testing for weekInfo interface of the internationalization API would be done like so:

if (Object.hasOwn(Intl.Locale.prototype, 'weekInfo')) {
        // weekInfo is available
}

The button can be hidden on the page by using the hidden attribute and then shown later. It can also be added later on page load. Try both solutions.

Reading list

Want more?

Back to top