0

I'm implementing the functionality of Autosaving data to clipboard after some interval (in my case I have used to save after 4 spaces). You can suggest interval.

I have followed this answer to copy textarea text to clipboard, here used a separate button to copy data to clipboard, however I want to save it continuously.

What I have tried so far:

var spaceCount = 0;
$('#description').keyup(function(event) {
  if (event.keyCode == 32) {
    ++spaceCount;
    if (spaceCount % 4 == 3) {
      $(this).select();
      try {
        var isCopied = document.execCommand('copy');
        console.log(isCopied);
        console.log("Copied to clipboard");
      } catch (e) {
        console.log("Error :Copying to clipboard");
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="description" cols="50" rows="4"></textarea>

The problem is the text remains selected. How can I deselect the text? I don't want to use any element to be created as I seen In one answer.

Or can you suggest another solution without using any plugin?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Shantaram Tupe
  • 1,646
  • 3
  • 16
  • 42

1 Answers1

0

You can clear the selected range using document.getSelection().removeAllRanges();. I have also added a bit of jQuery to put the cursor back to the end of the text in the textarea.

var spaceCount = 0;
$('#description').keyup(function(event) {
  if (event.keyCode == 32) {
    ++spaceCount;
    if (spaceCount % 4 == 3) {
      $(this).select();
      try {
        var isCopied = document.execCommand('copy');
        console.log(isCopied);
        console.log("Copied to clipboard");

        // clear the selected range here
        document.getSelection().removeAllRanges();
        // put the cursor back at the end of the text 
        var val = $(this).val();
        $(this).focus().val("").val(val);

      } catch (e) {
        console.log("Error :Copying to clipboard");
      }
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="description" cols="50" rows="4"></textarea>
Stuart
  • 6,630
  • 2
  • 24
  • 40