Monday 11 March 2024

javascript or jquery or angular or React copy table clipboard data with html and css

 This code snippet represents an HTML structure with a button, a table, and a script. Let's break down the components:


<button style="float: right;" id="btnCopy" type="submit" class="btn btn-primary  btn-rounded text-white font-weight-bold m-0 w-20 copyButton" onclick="contentsSelectElement( document.getElementById('copyTable'))">Copy Data</button>


  • This button has the text "Copy Data" displayed on it.

  • It has an ID attribute btnCopy.

  • It has inline styles for alignment (float: right;) and some Bootstrap classes (btn, btn-primary, etc.) for styling.

<style>
    table, th, td {
      border: 1px solid black;
      border-collapse: collapse;
    }
</style>
<table style="border: 1px solid" id="copyTable">
  <!-- Table content goes here -->
</table>



This part defines the table's styling, specifying that the table, table header cells (th), and table data cells (td) should have a black border of 1px width and collapsed borders.


Table Content:

The table has a structure with headers (<thead>) and body (<tbody>). It contains rows and columns of data.

<script type="text/javascript">
    function contentsSelectElement(el) {
        // Function to copy the contents of an element
       
        var notifyText = "Copied Successfully.";
        var body = document.body, range, sel;
        if (document.createRange && window.getSelection) {
            // Executing if the browser supports modern selection APIs
            range = document.createRange();
            sel = window.getSelection();
            sel.removeAllRanges();
            try {
                range.selectNodeContents(el);
                sel.addRange(range);
            } catch (e) {
                range.selectNode(el);
                sel.addRange(range);
            }
            document.execCommand("copy"); // Copy the selected content to clipboard
            alert(notifyText); // Show an alert notifying successful copy
        } else if (body.createTextRange) {
            // For older versions of Internet Explorer
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
            range.execCommand("Copy");
        }
    }
</script>


  • This script defines a function contentsSelectElement(el) that's called when the button is clicked.

  • It's designed to copy the contents of an HTML element (el) to the clipboard.

  • It checks for the browser's capability to use modern selection APIs (document.createRange and window.getSelection).

  • If supported, it creates a selection range, selects the content, and executes the copy command.

  • It also handles copying for older versions of Internet Explorer using createTextRange.

  • After copying, it shows an alert notifying the user that the content has been successfully copied.

Overall, this code provides functionality for copying the content of a table to the clipboard when the "Copy Data" button is clicked. It utilizes modern JavaScript APIs for selection and copying, with a fallback mechanism for older browser versions.



Full Code Example : 


<button style="float: right;" id="btnCopy" type="submit" class="btn btn-primary  btn-rounded text-white font-weight-bold m-0 w-20 copyButton" onclick="contentsSelectElement( document.getElementById('copyTable'))">Copy Data</button>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
<table style="border: 1px solid" id="copyTable">
  <thead>
      <tr>
        <td style="border-top:0;text-align: left;" colspan="4" class="blue-grey-text">
            <h4 style="display:inline-block; font-size: 14px;" class="blue-grey-text">PO No : 1234</h4>
        </td>
      </tr>
      <tr style="font-size:12px;">
        <th>Segment</th>
        <th>CPI(USD)</th>
        <th>Approved</th>
        <th>Cost</th>
      </tr>
  </thead>
  <tbody>
      <tr style="text-align:center;">
        <td class="blue-grey-text">Projects 1</td>
        <td class="blue-grey-text">0.1</td>
        <td class="blue-grey-text">0 </td>
        <td class="blue-grey-text">0</td>
      </tr>
      <tr>
        <th></th>
        <th></th>
        <th>Total Approved : 0</th>
        <th>Total Cost : USD 0</th>
      </tr>
  </tbody>
</table>
<script type="text/javascript">
    function contentsSelectElement(el) {
   
        var notifyText      = "Copied Successfully.";
        var body = document.body, range, sel;
        if (document.createRange && window.getSelection) {
            range = document.createRange();
            sel = window.getSelection();
            sel.removeAllRanges();
            try {
                range.selectNodeContents(el);
                sel.addRange(range);
            } catch (e) {
                range.selectNode(el);
                sel.addRange(range);
            }
            document.execCommand("copy");                   
            alert(notifyText);
        } else if (body.createTextRange) {
            range = body.createTextRange();
            range.moveToElementText(el);
            range.select();
            range.execCommand("Copy");
           
        }
    }
</script>


Angular


copy-table.component.ts



import { Component } from '@angular/core';

@Component({
  selector: 'app-copy-table',
  templateUrl: './copy-table.component.html',
  styleUrls: ['./copy-table.component.css']
})
export class CopyTableComponent {
  notifyText = "Copied Successfully.";

  constructor() { }

  copyData(el: HTMLElement) {
    const range = document.createRange();
    const sel = window.getSelection();
    if (sel) {
      range.selectNodeContents(el);
      sel.removeAllRanges();
      sel.addRange(range);
      document.execCommand("copy");
      alert(this.notifyText);
    }
  }
}



copy-table.component.html



<button style="float: right;" type="button" class="btn btn-primary btn-rounded text-white font-weight-bold m-0 w-20 copyButton" (click)="copyData(copyTable)">
  Copy Data
</button>

<style>
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
</style>

<table style="border: 1px solid" #copyTable>
  <thead>
    <tr>
      <td style="border-top:0;text-align: left;" colspan="4" class="blue-grey-text">
        <h4 style="display:inline-block; font-size: 14px;" class="blue-grey-text">PO No : 1234</h4>
      </td>
    </tr>
    <tr style="font-size:12px;">
      <th>Segment</th>
      <th>CPI(USD)</th>
      <th>Approved</th>
      <th>Cost</th>
    </tr>
  </thead>
  <tbody>
    <tr style="text-align:center;">
      <td class="blue-grey-text">Projects 1</td>
      <td class="blue-grey-text">0.1</td>
      <td class="blue-grey-text">0 </td>
      <td class="blue-grey-text">0</td>
    </tr>
    <tr>
      <th></th>
      <th></th>
      <th>Total Approved : 0</th>
      <th>Total Cost : USD 0</th>
    </tr>
  </tbody>
</table>



In this code:

  • The Angular component class CopyTableComponent contains a method copyData that handles copying data from the table. It selects the contents of the table element and copies it to the clipboard.

  • In the HTML template, (click)="copyData(copyTable)" is used to trigger the copyData method when the button is clicked.

  • The #copyTable template reference variable is used to reference the table element in the component class.

  • Styles are included within the component's template for simplicity. However, you can move them to a separate CSS file and import it into the component if needed.




React js


import React from 'react';

class CopyTableComponent extends React.Component {
    constructor(props) {
        super(props);
        this.copyTableRef = React.createRef();
    }

    copyData = () => {
        const el = this.copyTableRef.current;
        const notifyText = "Copied Successfully.";
        const range = document.createRange();
        const sel = window.getSelection();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
        document.execCommand("copy");
        alert(notifyText);
    }

    render() {
        return (
            <div>
                <button style={{ float: 'right' }} type="submit" className="btn btn-primary btn-rounded text-white font-weight-bold m-0 w-20 copyButton" onClick={this.copyData}>Copy Data</button>
                <table style={{ border: '1px solid' }} id="copyTable" ref={this.copyTableRef}>
                    <thead>
                        <tr>
                            <td style={{ borderTop: '0', textAlign: 'left' }} colSpan="4" className="blue-grey-text">
                                <h4 style={{ display: 'inline-block', fontSize: '14px' }} className="blue-grey-text">PO No : 1234</h4>
                            </td>
                        </tr>
                        <tr style={{ fontSize: '12px' }}>
                            <th>Segment</th>
                            <th>CPI(USD)</th>
                            <th>Approved</th>
                            <th>Cost</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr style={{ textAlign: 'center' }}>
                            <td className="blue-grey-text">Projects 1</td>
                            <td className="blue-grey-text">0.1</td>
                            <td className="blue-grey-text">0</td>
                            <td className="blue-grey-text">0</td>
                        </tr>
                        <tr>
                            <th></th>
                            <th></th>
                            <th>Total Approved : 0</th>
                            <th>Total Cost : USD 0</th>
                        </tr>
                    </tbody>
                </table>
            </div>
        );
    }
}

export default CopyTableComponent;


This code defines a React component named CopyTableComponent. It renders the table and button elements, and it handles the click event of the button to copy the table data. The ref attribute is used to reference the table element so that its content can be selected for copying.