S
S
Serginyo902017-11-10 14:44:55
JavaScript
Serginyo90, 2017-11-10 14:44:55

Copy text to clipboard using JS?

Hello.
I don't understand why the text is copied only when the button is double clicked?
Of course, I wrote a crutch, but it's still interesting to figure it out.

<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
          <div class="form-group">
            <h2><label for="jsonScript">JSON</label></h2>
            <textarea name="jsonScript" id="jsonScript" class="form-control jsonScript" rows="15">
            </textarea>
          </div>
          <div style="margin-top: 15px;">
            <button class="btn btn-default" onclick="copy()">Скопировать</button>
          </div>
      </div>

function copy(){
   var copyText = document.querySelector('#jsonScript');
   var range = document.createRange();
   var selectRange = range.selectNode(copyText);
   window.getSelection().addRange(range);
   window.getSelection().removeAllRanges();
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dilik Pulatov, 2017-11-10
@dilikpulatov

better use zClip

S
Stalker_RED, 2017-12-22
@Stalker_RED

function copy(){
  document.querySelector('#jsonScript').select()
  document.execCommand('copy')
}
https://jsfiddle.net/wyn0c63e/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question