Capture the contents of a table cell and store it in the clipboard

Is there a way to create a hover copy button in a table cell without actually placing the button inside the <td> tags? The goal is to allow users to easily copy text from a specific column cell by hovering over it.

function myFunction() {

  var copyText = document.getElementById("table-cell");

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
<table class="table">
  <thead>
    <tr>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="table-cell">Mark <button onclick="myFunction()">Copy text</button></td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>

      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Answer №1

Give this a shot and see if it can assist you:

Extract text by hovering over a table cell:

document.querySelectorAll(".table-cell").forEach(function(elm){
elm.addEventListener("mouseover", function(e){
 e.target.style.backgroundColor = 'red'; 
  var copyText = e.target.textContent; 
   const el = document.createElement('textarea');
  el.value = copyText;
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);

 
  /* Alert the copied text */
  alert("Copied the text: " + el.value);
  
});

})
<table class="table">
  <thead>
    <tr>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="table-cell">Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>
      <td class="table-cell">Jacob </td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <td class="table-cell">Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Answer №2

Given the lack of specific requirements from your end, I have taken the liberty to devise a solution independently.

function myFunction() {

  var copyText = document.getElementById("table-cell");

  /* Copy the text inside the text field */
  document.execCommand("copy");

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
#table-cell {
  position: relative;
}

#table-cell p{
   display: none;
   position: absolute;
   font-size: 10px;
   margin: 0;
   top: 0;
   cursor: pointer;
   color: blue;
   transition: .3s;
}

.table tr:hover #table-cell p {
   display: block;
}

.table #table-cell p:hover {
   transform: scale(1.3);
}
<table class="table">
  <thead>
    <tr>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td id="table-cell">Mark <p onclick="myFunction()">Copy text</p></td>
      <td>Otto</td>
      <td>@mdo</td>
    </tr>
    <tr>

      <td id="table-cell">Jacob <p onclick="myFunction()">Copy text</p></td>
      <td>Thornton</td>
      <td>@fat</td>
    </tr>
    <tr>
      <td id="table-cell">Larry <p onclick="myFunction()">Copy text</p></td>
      <td>the Bird</td>
      <td>@twitter</td>
    </tr>
  </tbody>
</table>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to effectively communicate and pass state information between sibling components in React?

Is there a way to share state data between two React component functions that are both children of another component? I am new to React and have tried exporting a const from my App.jsx file with a structure containing the state properties, but when queri ...

What's the secret behind generating a crisp 400 on paper?

Understanding Why it Prints 400 I'm struggling to comprehend the logic behind this var x = {}, y = { key: "y" }, z = { key: "z" }; x[y] = 100; x[z] = 200; console.log(x[y] + x[z]); ...

Removing the restriction on maximum width to 100% and allowing for automatic height adjustment

Within my project, I have implemented a CSS technique where all images within a container are set with the attributes max-width: 100%; and height: auto;. This is done to ensure that images scale down appropriately when the viewport and container size decre ...

The resizing issue persists with Angularjs charts

I have recently developed a small web application using AngularJS and I have implemented two charts from the AngularJS library - a bar chart and a pie chart. Although both charts are rendering correctly, they are not resizing properly as the display size c ...

Ways to declare a function within the events onMouseOver and onMouseOut

<div align="right" style="border:1 #FF0 solid; background-color:#999" onMouseOver="javascript: function(){this.style.backgroundColor = '#DDD';}" onMouseOut="javascript: function(){this.style.backgroundColor = '#999';}"> Register & ...

Select dropdown in AngularJS for Date formatting

After retrieving json data from a web API, I found that it contains a series of datetimes. My goal is to select a specific datetime from a dropdown list. While I can populate the list without any issues, the formatting appears to be incorrect and I'm ...

Prevent incorrect data input by users - Enhancing JavaScript IP address validation

I have been trying to create a masked input field for entering IP addresses, but every solution I come across seems to have some flaws. The best solution I found so far is , but it still allows values higher than 255 to be entered. It works fine initially ...

Do we always need to incorporate components in Vue.js, even if there are no plans for reuse?

I've been pondering this question for some time now: is it necessary for every component to be reusable? Consider a scenario where we have HTML, CSS, and JavaScript that cannot be reused. For instance, a CRUD table designed specifically for managing u ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

Strategies for troubleshooting asynchronous JavaScript with multiple script loading

Typically, I am familiar with setting breakpoints, inspecting variables, and stepping into functions. The file Default.htm contains numerous scripts and empty placeholders. I prefer to proceed through debugging step-by-step. Unfortunately, setting a brea ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

How can I identify the blur or focusout event in a tinyMCE textarea?

I have been tackling with an existing project. Whenever I click on some editable text within the webpage, it transforms into a textarea and shows the tinyMCE toolbar. However, when I click outside of that textarea, the toolbar disappears. I am trying to fi ...

Ways to verify if two items within a collection of objects share a common value in MongoDB

I have a collection of data called users stored in mongoDB that has the following structure: _id: ObjectId, sports: [ { name: 'cricket', history: [ { from: 10, to: 30 }, { from: 30, to: ...

Communicate through PHP and JavaScript chat to display HTML content in the chat window

I have been attempting to display HTML output in the chat window but instead, it is showing the HTML code. Here are the two files involved in the chat system: chat.js `function chatHeartbeat(){ var itemsfound = 0; if (windowFocus == false) { var ...

When I changed the encoding of a live texture to sRGB in Three.js, the frame rate dropped by fifty percent

I am currently working on a threejs application that requires updating a texture in each frame. The output encoding of the THREE.WebGLRenderer is set to sRGB. Upon setting the texture encoding to sRGB, I observed that the rendering result is accurate. How ...

Instead of displaying the location attribute in an alert, populate it into a text area

I have a function that can retrieve my current location using longitude and latitude coordinates. However, I am looking to automatically fill a text area (Populate Here) with the results instead of displaying an alert. <!DOCTYPE html> <html> ...

Incorporate a prefix into the URL of Angular development servers

When our application is in production, it will not be served from the root. Instead, it will be served from something like https://ourdomain.com/ourapp. This setup is causing problems with image URLs. To work around this issue, I am trying to serve the ap ...

Malfunction in function calling due to improper ajax response (JSON)

There seems to be an issue with the success function not being executed in the JavaScript code below: $.ajax({ type: 'POST', url: 'http://localhost/hf_latest_desktop/st_pages/user_area/acc_buttons/pass_change/pass_ ...

Troubleshooting error in data structure for nested dynamic routes with Next.js getStaticPaths

I am working on a page called [categories][price].js and I am attempting to achieve a particular data structure within the getStaticPaths function. For example, I want to have paths like cat1/10, cat1/20, cat1/30, cat2/10, cat2/20, etc. I came across this ...