MineGlade
MineGlade

Reputation: 37

js copy function not working in html

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?

Upvotes: 0

Views: 1075

Answers (2)

Sanjay Kumar Singh
Sanjay Kumar Singh

Reputation: 937

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>

Upvotes: 6

Nikanor
Nikanor

Reputation: 262

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.

Upvotes: 0

Related Questions