ArticleZip > Copy Selected Text To The Clipboard Without Using Flash Must Be Cross Browser

Copy Selected Text To The Clipboard Without Using Flash Must Be Cross Browser

Have you ever needed to copy some text from a webpage without relying on Flash or any browser-specific solutions? In this article, we'll explore a straightforward way to accomplish this task using simple JavaScript code that works across various browsers.

First things first, let's set the goal: to enable users to copy selected text from a webpage to their clipboard with just a few clicks. The trick here is to create a streamlined experience that doesn't depend on outdated technologies like Flash.

To kick things off, we need to write some JavaScript code that detects user-selected text and copies it to the clipboard. Here's the basic structure of the code:

Javascript

function copyTextToClipboard() {
  var text = window.getSelection().toString();
  
  var dummyElement = document.createElement("textarea");
  document.body.appendChild(dummyElement);
  dummyElement.value = text;
  dummyElement.select();
  document.execCommand("copy");
  document.body.removeChild(dummyElement);
}

Let's break this down step by step:

1. We start by retrieving the selected text using `window.getSelection().toString()`.
2. Next, we create a temporary element (`