Duplicate the content by selecting the text and clicking on the button

After clicking on a table cell, I can copy the text but not after clicking on a button. Any suggestions on how to solve this issue? I suspect the problem might be in this line of JS:

const el = document.createElement('textarea');
, but I'm unsure. https://codepen.io/S4UCY/pen/abNpyWB

/* Copy after clicking on text */
document.querySelectorAll(".table-cell").forEach(function(elm){
elm.addEventListener("click", function(e){
 e.target.style.backgroundColor = 'green'; 
  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);
  
});

})



function myFunction() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*For mobile devices*/

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

  /* Alert the copied text */
  alert("Copied the text: " + copyText.value);
}
td button{
    float: right;
}

td button:before {
  content: "Copy";
}
<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" id="myInput" scope="row">kaching<button onclick="myFunction()" type="button" name="button"></button></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 №1

Instead of adding functionality to the button, consider letting the click event propagate up to the parent <li> element and handle everything in its listener.

document.querySelectorAll(".table-cell").forEach(function(elm) {
  elm.addEventListener("click", copyText);
})

function copyText(e) {
  const td = e.currentTarget;
  td.style.backgroundColor = 'green';
  var copyText = td.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);
}
td button {
  float: right;
}

td button:before {
  content: "Copy";
}
<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" id="myInput" scope="row">kaching<button type="button" name="button"></button></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

The occurrence of this issue can be attributed to the fact that when the button is clicked, it attempts to copy its own text rather than the content of the table cell.

elm.addEventListener("click", function(e){
    e.target.style.backgroundColor = 'green'; 
    var copyText = e.target.textContent; // in this case, "e" refers to the button element
   ...
}

Answer №3

After considering your issue, I devised a unique solution. Instead of directly calling onclick="myFunction()", I decided to implement tag validation within the eventListener function to ensure that the element was a button. By doing so, I eliminated the need for the deprecated myFunction() and streamlined the code by preventing duplication.

/* Copy after clicking on text */
document.querySelectorAll(".table-cell").forEach(function(elm){
elm.addEventListener("click", function(e){
  var copyText;
  if(e.target.tagName == "BUTTON") { // <----- Validation
    /* Get the text field by searching for the cell */
    var elem = document.getElementById("myInput");
    elem.style.backgroundColor = 'green'; 
    copyText = elem.textContent;
  } else {
    /* Get the text field directly */
    e.target.style.backgroundColor = 'green'; 
    copyText = e.target.textContent;
  }
  
  const el = document.createElement('textarea');
  el.value = copyText;
  document.body.appendChild(el);

  /* Select the text field */
  el.select();
  el.setSelectionRange(0, 99999); /*For mobile devices*/

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

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

})

function myFunction() {} // <------ Removed
td button{
    float: right;
}

td button:before {
  content: "Copy";
}
<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" id="myInput" scope="row">kaching<button type="button" name="button"></button></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 №4

This is the cause of the issue

elm.addEventListener("click", function(e){
    e.target.style.backgroundColor = 'green'; 
    var copyText = e.target.textContent; // when the button is clicked, "e" refers to the button
   ...
}

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

CSS transform: applying the same CSS to multiple divs results in a variety of different outcomes

I am working on creating multiple parallelograms with the same skew aligned horizontally. While the first one looks perfect, additional divs seem to increase the skew more and more. I even attempted this using images and applying transform: rotate() but en ...

Getting Session from Next-Auth in API Route: A Step-by-Step Guide

When printing my session from Next Auth in a component like this, I can easily see all of its data. const session = useSession(); // ... <p>{JSON.stringify(session)}</p> I am facing an issue where I need to access the content of the session i ...

Instead of broadcasting your message to the channel, try sending it directly to the user

While attempting to send this embed to a user's DMs instead of a channel, I have encountered numerous outdated and irrelevant posts that do not address my specific question. module.exports = { name: 'help', description: 'this is a ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

Improperly removing a draggable element in jQueryUI can cause unexpected behavior

I'm currently developing a visual editor that enables users to manipulate elements by adding, removing, and dragging them around as desired. Each element is represented as a div and made draggable using jQueryUI. When new elements are added, they are ...

JS values are completely out of sync

I am currently computing values, capturing them in a snapshot, and then sending them within an interval. However, the problem lies in the fact that the total sum is growing at an unexpectedly high rate. Here are the calculations being performed: // Ass ...

Encountering a 400 Bad Request error while using the SharePoint 2013 Rest API

I am currently developing a web component that utilizes jQuery for making a REST API request to rename a SharePoint subsite. The functionality is working as expected when using a custom button on EditForm.aspx within a list, and it also functions correctly ...

Using a conditional statement in a JavaScript loop

Here is the data I have: companyList: [ { company_name: 'company1', item: 'item1' }, { company_name: 'company1', item: 'item2' }, { company_n ...

The ng-click function for the button is malfunctioning when viewed on a mobile device within the datatable

Can anyone assist in troubleshooting why the ng-click function is not working on the mobile view of Datatable? <tr class="child"> <td class="child" colspan="3"> <ul data-dtr-index="0"> <li data-dtr-ind ...

Preventing HTML entities from expanding in the HTML::TreeBuilder Perl module

Below is a snippet of code to examine: #!/usr/bin/perl use strict; use HTML::TreeBuilder; sub test { my ($content) = @_; my $tree = HTML::TreeBuilder->new; $tree->implicit_tags(0); $tree->no_expand_entities(1); $tree->parse_conte ...

Troubleshooting Blade Template HTML Coloration Problem in Atom

When I include Laravel code inside the HTML element itself, it causes all subsequent HTML elements to appear discolored. For example, <body @php language_attributes() @endphp> will cause </body> to be discolored. However, if I use plain PHP i ...

Interested in incorporating href within a PHP variable?

My goal is to send a verification email without displaying the link in the email itself. Instead, I want to include text that says "click here to verify." { $verify_email=" Hello, Thank you for signing up. To verify your e-mail, please visit http://".$sit ...

Switch effortlessly between various THREE.EffectComposer scenes with a single renderer in three.js

Currently, I'm experimenting with creating intricate scenes using Composer in three.js. I'm curious to know if it's achievable to switch between two scenes with distinct composer effects applied to them. To better understand this concept, I& ...

Steps for creating an npm package from the /build folder of Create React App

Hello! I am currently working on an app developed using the create-react-app boilerplate. After compiling and building it with npm run build, I now want to transform the /build folder into an npm package for easy use in other projects as a micro app. Can ...

Accessing a menu through key input

At the top of my webpage, there is a menu. jQuery(document).ready(function() { jQuery(".clickMeToOpenMenu").toggle(function() { jQuery('#menu').stop().animate({'height':'500px'}, 500) }, function() { ...

I am curious if it is possible to generate a dynamic table content by utilizing an ajax get request to retrieve and parse json data

I am completely new to Javascript and struggling with creating a dynamic table that populates its contents based on "product data" submitted through a form (such as image, brand, model, screensize, os). Despite trying multiple approaches, nothing seems to ...

What could be causing the onclick function in the button tag to malfunction?

I have implemented a feature where clicking on a "Delete Photo" button would trigger the appearance of another delete button in the code. The code for this functionality is as follows: <button type="button" class="btn btn-danger" onc ...

Transferring information between Flask and JS using AJAX for a Chrome extension

I'm experimenting with AJAX calls to establish communication between my Javascript frontend in a chrome extension and the Flask API where I intend to utilize my Machine Learning algorithms. content.js console.log("Let's get this application ...

The selectize feature is failing to show search results

I am attempting to incorporate Remote Source in Selectize. I am retrieving data from an API. The format is as follows: concept_id,name 228,Pelecypoda 286,Pelecypoda When I attempt to log the item in the render function, it does not show up in the consol ...

Encountering difficulties with uploading files and images in a Node.js environment

Currently, I am learning node js and express js on Tutorial Point. In the course, I attempted to upload a document but encountered an error that says "Cannot read property 'file' of undefined." Can someone please assist me in resolving this issue ...