Copy text to clipboard upon keypress

923 views Asked by At

It is possible to use this library to bind copy to clipboard to a keyboard short-cut?

All the usage examples assume there's a button on the page and wait until the user presses that button. But I need to trigger it with the keyboard.

My attempts don't even trigger any callback. I've there's a trigger I need to issue manually, I can't find it:

jQuery(function($){
  var $placeholder = $("div:first");
  var clipboard = new ClipboardJS($placeholder[0]);
  
  $("textarea").on("keyup", function(event){
    var text;

    if (event.key === "s") {
      text = "Test / " + Math.round(1000000 * Math.random());
      console.log("Copying '%s' to clipboard...", text);
      $placeholder.attr("data-clipboard-text", text);

      clipboard.on('success', function(e) {
        console.info('Action:', e.action);
        console.info('Text:', e.text);
        console.info('Trigger:', e.trigger);
        e.clearSelection();
      });
      clipboard.on('error', function(e) {
        console.error('Action:', e.action);
        console.error('Trigger:', e.trigger);
      });
      // And now what?
    }
  })
});
textarea{
  width: 100%;
  color: red;
}
textarea:focus{
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<textarea>Type "s" here to save some text to clipboard. Then use Ctrl+V to see if it worked.</textarea>
<div></div>

2

There are 2 answers

1
Álvaro González On BEST ANSWER

I think I found the point I was missing. I basically need to trigger the click event myself. I've replaced my <div> place-holder with something more obvious:

jQuery(function($){
  var $dummyButton = $("button:first");
  var clipboard = new ClipboardJS($dummyButton[0]);
  clipboard.on('success', function(e) {
    console.info('Action:', e.action);
    console.info('Text:', e.text);
    console.info('Trigger:', e.trigger);
    e.clearSelection();
  });
  clipboard.on('error', function(e) {
    console.error('Action:', e.action);
    console.error('Trigger:', e.trigger);
  });

  $("textarea").on("keyup", function(event){
    var text;

    if (event.key === "s") {
      text = "Test / " + Math.round(1000000 * Math.random());
      console.log("Copying '%s' to clipboard...", text);
      $dummyButton.attr("data-clipboard-text", text);

      $dummyButton.trigger("click");
    }
  })
});
textarea{
  width: 100%;
  color: red;
}
textarea:focus{
  color: green;
}
button {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<textarea>Type "s" here to save some text to clipboard. Then use Ctrl+V to see if it worked.</textarea>
<button>Dummy button</button>

This works in desktop browsers like Firefox, Chrome, Edge, IE11 (this browser asks the user for permission) and possibly many others.

0
Raine Revere On

Solution without jQuery:

/** Copies a string directly to the clipboard with a simulated button click. */
const copy = s => {
  const dummyButton = document.createElement('button')
  const clipboard = new ClipboardJS(dummyButton, { text: () => s })
  dummyButton.click()
}

// copy on keydown
window.addEventListener('keydown', e => {
  if (e.key === 's') {
    copy('Hello universe')
  }
})

The browser focus will move to the dummy button element, so you may need to restore the focus afterwards with el.focus().