Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot copy draggable element unless sibling is clicked first

If an element with a copy event bound to it has an element with draggable inside of it, the copy event is not fired unless you first click on a non-draggable sibling.

Here is the code:

<div id='copy'>
  <div draggable='true'>Draggable</div>
  <div>Non-draggable</div>
</div>
const copy = document.getElementById('copy');

copy.addEventListener('copy', (e) => {
    alert('copied');
});

https://jsfiddle.net/pg4f0usx/

Replication steps:

  • Run the fiddle
  • Click on the draggable element and press Ctrl-C - nothing will happen
  • Click on the non-draggable element and press Ctrl-C - the 'copied' alert will pop up
  • Click on the draggable element and press Ctrl-C - the 'copied' alert will pop up

This happens in both FireFox and Chrome. Is there a way to avoid needing to click on the non-draggable element for the copy event to be fired on the parent element?

like image 713
Schiem Avatar asked Nov 08 '25 00:11

Schiem


1 Answers

You can attach the copy event in the window so that you don't need to click on that div. But you need to be in that window (at least clicking somewhere)

    window.addEventListener('copy', (e) => {
        e.preventDefault();
        e.clipboardData.setData('text/plain', 'copied data');
      alert('copied');
    });
<div id='copy'>
      <div draggable='true'>Draggable</div>
      <div>Non-draggable</div>
</div>
<div id='outro'>
  <span style='background-color:gray; align-items: center; padding:50px; padding-top: 0px; '>If you are anywhere in the page (like here)  it will copy with CTRL + C</span>
</div>
like image 155
testing_22 Avatar answered Nov 10 '25 20:11

testing_22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!