Sample For Copy Grid

by bhatnagar018

HTML

<div id="myelement">
  <table>
    <thead>
      <tr>
        <td>Head 1</td>
        <td>Head 2</td>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
    </tbody>
  </table>
</div>
<div style="clear:both;">
</div>
<button onclick="foo()">
  Copy
</button>

CSS

table {
  background: #00ff00;
  color: red;
}

td {
  text-align: left;
}

JavaScript

function foo() {
  if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
    var myelement = document.getElementById('myelement');
    //console.log(myelement.select());

    var sel;
    // IE
    if (document.selection) {
      var sel = document.body.createTextRange();
      sel.moveToElementText(myelement);
      sel.select();
    } else {
      var sel = document.createRange();
      sel.setStartBefore(myelement);
      sel.setEndAfter(myelement);
      window.getSelection().addRange(sel);
    }

    try {
      //window.getSelection().setPosition(myelement.firstChild.firstChild, 5);
      //return document.execCommand('copy', false, null);
      return myelement.execCommand("copy", false, null); // Security exception may be thrown by some browsers.
    } catch (ex) {
      console.log(ex);
      return false;
    }
  }

  /*if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
    try {
      var myelement = document.getElementById('#myelement'),
        range = document.createRange();

      range.selectNode(myelement);
      window.getSelection().addRange(range);
    } catch (ex) {
      console.log(ex);
      return false;
    }
  }*/

}


/*
function foo() {
  var el = document.getElementById('myelement'),
    commandName = "copy";
  if (typeof value == "undefined") {
    value = null;
  }

  if (typeof window.getSelection != "undefined") {
    // Non-IE case
    

    // Temporarily enable designMode so that
    // document.execCommand() will work
    document.designMode = "on";

    var sel = document.createRange();
    sel.setStartBefore(el);
    sel.setEndAfter(el);
    window.getSelection().addRange(sel);

    // Execute the command
    document.execCommand(commandName, false, value);

    // Disable designMode
    document.designMode = "off";

    
   
  } else if (typeof document.body.createTextRange != "undefined") {
    // IE case
    var textRange = document.body.createTextRange();
   ...