Search code examples
javascriptdom-eventscopy-paste

Copy to clipboard on hover


I am trying to copy text to clipboard on hover and noticed that it only works on click (document.body.addEventListener('click', copy, true);), but when you try to trigger copy on hover it doesn't work (document.body.addEventListener('mouseover', copy, true);). I was playing around with this example and was wondering why that is the case.


Solution

  • document.execCommand needs a user event to work. It will not work on hover, but it will on clicks and the like (mousedown, mouseup, etc.).

    You still might want to check compatibility (here). Refer to this original answer and (this) jsFiddle. It seems browsers do support it consistently now, but you still need to make sure you want to target those versions in the table.

    $('.big').hover(function () {
        // will not work, no user action
      $('input').select();
        document.execCommand('copy');
    });
    
    $('.big').mousedown(function () {
        //works
      document.execCommand('copy');
    });
    

    Copy commands triggered from document.execCommand() will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this. How implementations can be configured to allow write access to the clipboard is outside the scope of this specification.