0

I'm trying to get a copy button on my html page but it won't work - in the chrome console it states nothing, it just won't copy the text.

this is my html:

<!doctype html>
<div class="ipDiv tk-saffran">
  <div class="ipText">
    <h2 id="ip">play.MineGlade.net</h2>
  </div>
  <div class="copyButton">
    <button onclick="copyIp()">Copy IP</button>
    <script>
      function copyIp() {
        var copyText = document.getElementById("ip");
        copyText.select;
        document.execCommand("Copy");
      }
    </script>
  </div>
</div>

how do I fix this?

MineGlade
  • 37
  • 6

2 Answers2

6

Here is easy and simple way to do copy, Please review this updated code

function copyIp()
{
    window.getSelection().selectAllChildren(document.getElementById("ip"));
    document.execCommand("Copy");
}
<div class="ipDiv tk-saffran">
    <div class="ipText">
        <h2 id="ip">play.MineGlade.net</h2>
    </div>
    <div class="copyButton">
        <button onclick="copyIp()">Copy IP</button>

    </div>
</div>
0

You are trying to select h2 content which will not work with select function, also you'r not calling it right it should be .select(). To select content of element please check this thread: How to select all text in contenteditable div?

Please see fiddle I made for you with your example

    <div class="ipDiv tk-saffran">
        <div class="ipText">
            <h2 id="ip">play.MineGlade.net</h2>
        </div>
        <div class="copyButton">
            <button onclick="copyIp()">Copy IP</button>
            <script>
                jQuery.fn.selectText = function(){
                   var doc = document;
                   var element = this[0];
                   console.log(this, element);
                   if (doc.body.createTextRange) {
                       var range = document.body.createTextRange();
                       range.moveToElementText(element);
                       range.select();
                   } else if (window.getSelection) {
                       var selection = window.getSelection();        
                       var range = document.createRange();
                       range.selectNodeContents(element);
                       selection.removeAllRanges();
                       selection.addRange(range);
                   }
                };
                function copyIp() {
                   $("#ip").selectText();
                   document.execCommand("Copy");
                }
            </script>
        </div>
    </div>

Make sure your include jquery with this to work.

Nikanor
  • 262
  • 1
  • 5
  • 17