Copy a text when a link or button is clicked

Copy a text when a link or button is clicked

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Copying Text on Click: A Modern Approach to Clipboard APIs

Implementing a "copy to clipboard" feature is a common requirement for sharing codes, API keys, or configuration snippets. While the concept seems simple, the implementation landscape has shifted dramatically over the last decade. The code snippet provided in older tutorials often relies on deprecated methods like execCommand("Copy") and text ranges, which are no longer recommended due to poor browser support and security concerns.

To achieve the behavior seen on sites like RetailMeNot today, you need to leverage the modern Clipboard API introduced in HTML5. This approach is cleaner, more secure, and works consistently across modern browsers without relying on legacy jQuery plugins or obscure DOM manipulation techniques.

The Modern Clipboard API

The core of any copy-to-clipboard solution lies in two specific methods: navigator.clipboard.writeText() for sending data to the clipboard and navigator.clipboard.readText() for retrieving it (though reading is often unnecessary). These methods operate asynchronously, meaning they return a Promise that resolves once the operation completes.

Unlike older methods that attempted to interact with the user's selection directly via invisible text ranges, the modern API asks the browser to handle the cut-and-paste logic internally. This abstraction handles the complex permission requirements and UI feedback automatically.

Here is how you might structure a simple function in vanilla JavaScript:

async function copyToClipboard(text) {
    try {
        await navigator.clipboard.writeText(text);
        console.log('Text copied to clipboard!');
    } catch (err) {
        console.error('Unable to copy text: ', err);
    }
}

This function is robust and handles potential errors gracefully. You can attach this logic to any HTML element using event listeners. For a link, you would add an onclick handler or use the addEventListener method within your script block. When triggered, it passes the specific string you wish to copy to the asynchronous writer.

Handling Permissions and Security Contexts

A critical distinction exists between the modern Clipboard API and older alternatives regarding security contexts. The modern navigator.clipboard interface is designed to run only in secure contexts (HTTPS or localhost). If your site serves content over HTTP, this API will throw a "Failed to execute 'writeText' on 'Clipboard': permission denied" error.

If you must support non-secure environments, developers often fall back to the legacy document.execCommand('copy') method. However, this is only viable if there is already user-selected text on the page or if you dynamically create a temporary element with that text, select it, and invoke the command. This fallback is more verbose and less reliable than the native API but remains an option for specific legacy requirements.

User Feedback and UX Considerations

Simply copying the text to the clipboard does not guarantee the user knows it happened. In modern web development, immediate visual feedback is essential. A common pattern involves changing the button or link style briefly after a successful copy event.

You can achieve this by toggling a CSS class on the trigger element upon success:

const link = document.querySelector('#my-link');
link.addEventListener('click', async () => {
    const textToCopy = "YourSecretCode123";
    
    await navigator.clipboard.writeText(textToCopy);
    
    // Provide visual feedback
    link.textContent = 'Copied!';
    setTimeout(() => {
        link.textContent = 'Click here to copy the Code';
    }, 2000);
});

This pattern improves usability by confirming the action without requiring a second click or navigating away. It also prevents users from feeling like their click had no effect, which is a common frustration with clipboard interactions.

Integrating with Frameworks

If you are building an application using Laravel or similar frameworks, the logic remains the same because these tools operate primarily on the frontend. You would simply include your JavaScript file in the view or use the asset pipeline to load it. The backend (PHP) is responsible only for generating the unique code string that needs to be copied; the actual clipboard manipulation happens entirely in the browser.

There is no need to invent complex server-side logic for this task. The separation of concerns keeps your application lightweight and secure, ensuring sensitive data isn't unnecessarily processed on the server after it has been generated.

Our network