Karolina Ticha
Karolina Ticha

Reputation: 531

Document.execCommand do not work as I expected

Here is my table

<table>
  <tr>
    <th>Name</th>
    <td>Paul Johnson</td>
    <th>Street</th>
    <td>Fake Street</td>
  </tr>
  <tr>
    <th>State</th>
    <td>California</td>
    <th>Car</th>
    <td>Cadillac</td>
  </tr>
</table>

My script is executed by mouseenter event:

$('th').on("mouseenter mouseleave", function(e) {if (e.type === 'mouseenter') {

});

Inside it its this toolbar which has inside link object

toolbar = $("<div />").css({
    "padding": "5px",
    "background" : "#F8F8F8",
    "borderRadius" : "5px 0 5px 5px"
  });

  var link = $("<a />").css({
    "display" : "block",
    "height" : "20px",
    "width" : "20px",
    "marginBottom" : "5px",
    "background-size" : "100%",
    "position" : "relative"})
    .attr({"target" : "_blank"});

My variable thisNext does that it get text of next td element

  var thisNext = $( $(this).next() ).text();

Question Why my var copy do not copy thisNext value altrough console.log works as I expected?

Edit : Goal is, if you click to "copy" object appended for exemple on th Name, to get into clipboard Paul Johnson. If on Street, then copy Fake street and so on.

var copy = link.clone().on("click", function (e) {
    e.preventDefault();
    console.log ("thisNext ");
    thisNext.execCommand('copy');
}

Upvotes: 1

Views: 380

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Working Pen

The problem come from the line :

thisNext.execCommand('copy');

The copy command copy always the selection so we have to select the content of the td first then execute the comment and finally reset the selection :

var copy = link.clone().on("click", function (e) {
    e.preventDefault();

    var td = e.target.parentNode.parentNode;

    do {
      td = td.nextSibling;
    } while(td && td.nodeType !== 1); // 1 == Node.ELEMENT_NODE

    var range = document.createRange();  

    range.selectNode(td); 

    window.getSelection().addRange(range);

    document.execCommand('copy');   

    // Remove the selections - NOTE: Should use
    // removeRange(range) when it is supported  
    window.getSelection().removeAllRanges();  
})

NOTE : you could check if your browser support the copy command using This link.

Hope this helps.

Upvotes: 1

Related Questions