Copy Text to Clipboard with JavaScript — Simple Example with One Function

Introduction

Copy Text to Clipboard with JavaScript is a simple and useful trick for web apps. Here’s a short function to copy any text to the clipboard.

How to Copy Text to Clipboard with JavaScript


function copyText(text) {
  navigator.clipboard.writeText(text)
    .then(() => alert(‘Text copied to clipboard!’))
    .catch(err => console.error(‘Failed to copy:’, err));
}

// Usage:
copyText(‘Hello, World!’);

How This Works

This Copy Text to Clipboard with JavaScript function uses navigator.clipboard.writeText() to copy text programmatically.

Why Use This?

It’s cleaner than relying on hidden inputs or execCommand hacks, and fully modern browser supported.

Common Mistake

Not handling .catch() properly can leave you wondering why your clipboard isn’t working.

Pro Tip

Wrap this in a reusable utility for all your projects.

Related Snippet

Bootstrap Alert Dismissible

2 thoughts on “Copy Text to Clipboard with JavaScript — Simple Example with One Function”

Leave a Comment