Copy Div Content When it is Clicked Using JavaScript

Copy Div Content When it is Clicked Using JavaScript

In this tutorial, we will learn how to create a JavaScript function that allows users to copy text from a specific div element when it is clicked. This can be a useful feature for allowing users to easily copy text from a webpage without the need for additional input elements or buttons.

We will start by creating a function that captures the text inside the div element and copies it to the clipboard using a temporary textarea element. Next, we will create a "Copied" message element and display it within the div.

Copy Div Content on Click using JavaScript Example

JavaScript Code:

function copyTextOnClick(divId) {
  // Get the text that needs to be copied
  var text = document.getElementById(divId).innerText;

  // Create a temporary textarea element to copy the text
  var textArea = document.createElement("textarea");
  const message = document.getElementById('msg');
  textArea.value = text;

  // Display a "Copied" message at the top right corner of the div = 'block';
      setTimeout(() => { = 'none';
      }, 2000);

This JavaScript function, named copyTextOnClick, takes a single parameter, divId, which is the ID of the div element that you want to copy text from.

The function first gets the text inside the div element by using document.getElementById to retrieve the div element and then accessing its innerText property.

Next, the function creates a temporary textarea element and sets its value to the text that needs to be copied. The textarea element is then added to the body of the webpage and selected. The document.execCommand("copy") method is then used to copy the text in the textarea element to the clipboard. The temporary textarea element is then removed from the body of the webpage.

Finally, the function displays a "Copied" message element by setting its display style to block, and then hides the message element after 2 seconds by setting its display style to none.

HTML Code:

<div id="myDiv" onclick="copyTextOnClick('myDiv')">
  Click here to copy this text
  <div id="msg">Copied...</div>

CSS Code:

#myDiv {
  width: 700px;
  border: 1px solid #ddd;
  background-color: #f5f5f5;
  padding: 5px;
  height: 100px;
  cursor: pointer;
#msg {
  position: relative;
  float: right;
  color: #000;
  background-color: #fff;
  display: none;
  padding: 5px 10px;
  border-radius: 6px;

You can check the live example on Codepen, if the below code does not run on your browser, due to the permissions issue, click on The "Edit on Codepen" to view it there:

See the Pen Untitled by Vinish Kapoor (@foxinfotech) on CodePen.