Recipe 22Copying Text to Clipboard with the Clipboard API

Task

Suppose you have a cooking website that provides recipes for different meals, and you want to provide readers with the option of copying the ingredients of the recipes to their clipboard so that they can create a shopping list. To achieve this, you need to create a button that, when clicked, copies the list of ingredients to the clipboard.

Solution

First, set up your HTML elements. You need a button that triggers a JavaScript code. Remember, your program should not attempt to read or write the user’s clipboard without permission. So, creating a button that clearly states it copies data to the clipboard is the first step:

 <!doctype html> ...

Get Text Processing with JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.