Search code examples
jqueryclipboard

jQuery Animation using copy clipboard


I want some animation on copi clipboard jQuery.

Ex : It show some highlights in color that how much text content copied , so if we have longer text so it will easy to understand how much text is left

Any suggestions on I tried to find lots of things but no luck yet

This is have done so far

$(".copyable").click(function() {
  $(".copyable").css("background-color", "");
  $(this).css("background-color", "red");
  navigator.clipboard.writeText($(this).text()).then(res => {
    $(this).css("background-color", "green");
  })
})

but it show background color but actual requirement is showing progress how text content copy


Solution

  • Use window.getSelection() to get the selected text. Then detect the position of the text within the paragraph, you would like to wrap the selected within a highlighted span.

    I make another callback to highlight the copy text by pressing the Control + C or Right click/Copy. Because Stackoverflow blocks the Clipboard API, so you cannot select to copy/highlight (as you want) the text below within the Stackoverflow scope, but it would work in another environment.

    Explain

    • First I use window.getSelection() method to get the selected text object. The Selection object gives me the Selection.anchorOffset and Selection.focusOffset of the text within the paragraph.
    • Use the Math.min() and Math.max() to detect the startIndex and endIndex of the selected text within the paragraph (the order reverse base on the direction you use your mouse to select the text)
    • I use the start and end index to divide the paragraph into 2 parts using the substring method. Then I wrap the selected text with a span.highlight tag, wrap part2 with another span. The reason I have to wrap the second part is to make the selection work properly after the first selected.
    • And that's it!

    $(".copyable").click((e) => {
      let selection = window.getSelection();
      navigator.clipboard.writeText(window.getSelection().toString())
        .then(res => {
          debugger;
          highlightCopiedText(e.target, selection);
        })
    });
    
    $(".copyable *").bind('copy', (e) => {
      // Get the text copied
      highlightCopiedText(e.target, window.getSelection());
    });
    
    // We use Selection to detect the position of the selected text within paragraph
    function highlightCopiedText(parentElement, selection) {
      let startIndexOfSelection = Math.min(selection.anchorOffset, selection.focusOffset);
      let endIndexOfSelection = Math.max(selection.anchorOffset, selection.focusOffset);
    
      // Using substring(). we devide the innerHTML into 2 parts, one before the selected and the second is the further
      // then wrap the selected text with a span.highlight
      // wrap the second part with a normal span
      // The reason why we have to wrap part2 in another span is to make the window.getSelection work properly the after the first copy
    
      let part1 = parentElement.innerHTML.substring(0, startIndexOfSelection );
      let part2 = `<span>${parentElement.innerHTML.substring(endIndexOfSelection )}</span>`;
      let replacement = `<span class="highlight">${selection.toString()}</span>`;
    
      parentElement.innerHTML = part1 + replacement + part2;
    }
    .highlight {
      color: green;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span class="copyable">
            <span>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum debitis harum explicabo!
                Aliquid debitis sit, reiciendis delectus aliquam reprehenderit blanditiis velit. Debitis, rerum aliquam
                maxime,
                doloribus, quam odit totam consectetur at porro earum autem iste neque laudantium eum numquam corrupti
                placeat
                dolorum! Dolorum asperiores quisquam fuga mollitia reiciendis consectetur aspernatur, veritatis cumque minus
                dolore at? Eveniet molestiae commodi, minima, recusandae similique reiciendis dolore alias doloremque totam
                ex,
            </span>
    </span>