0

I have the following function that copies text in a div to the clipboard. After 3 seconds I would like it to deselect the text. I can't get it to deselect the text in the div via the setTimeout. I have tried blur, trigger and click. Is there a solution?

function copyUsingJquery(element_id) {
        $(element_id).attr("contenteditable", true)
          .select()
          .on("focus", function () {
              document.execCommand('selectAll', false, null)
          })
          .focus();
        document.execCommand("Copy");
        $(element_id).removeAttr("contenteditable");

        setTimeout(function () {
            //deslect text on page after a few seconds
            $(element_id).trigger("click");
        }, 3000);

    }
Rob
  • 1,226
  • 3
  • 23
  • 41

2 Answers2

0

Working solution:

       function copyUsingJquery(element_id) {
            $(element_id).attr("contenteditable", true)
              .select()
              .on("focus", function () {
                  document.execCommand('selectAll', false, null)
              })
              .focus();
            document.execCommand("Copy");
            $(element_id).removeAttr("contenteditable");

            setTimeout(function () {
                //deslect text on page after a few seconds
                //$(element_id).trigger("blur");
                window.getSelection().removeAllRanges();
            }, 3000);    
        }
Rob
  • 1,226
  • 3
  • 23
  • 41
0

You don't need jQuery for this. Here's a direct translation of your jQuery code.

const unselect = () => window.getSelection().removeAllRanges()

function copyWithoutJQuery(elementId) {
  const el = document.getElementById(elementId)
  el.setAttribute('contenteditable', true)
  el.addEventListener('focus', () => {
    document.execCommand('selectAll', false, null);
    document.execCommand('Copy');
    el.removeAttribute('contenteditable');
    setTimeout(unselect, 3000);
  })

  el.focus();

  const range = document.createRange();
        range.selectNodeContents(el);
  const selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
}
Benny Powers
  • 5,398
  • 4
  • 32
  • 55