Search code examples
javascriptjqueryclipboard

Copy to clipboard javascript not working in Mobile devices. What is the issue?


The following code is not working on Mobile devices. But works on desktops. What is the issue here?

$(document).ready(function()
{
  copy();
})

function copy() {
  var txt = document.getElementById("result");
  navigator.clipboard.writeText(txt.innerText);    
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result">copy text</div>


Solution

  • I am answering my own question as i found a clean way to do this. I found a better jQuery library to do this job.

    Just reference this library:

    https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js

    Then the texts that need to copy should go for the "data-clipboard-text"

     <button id="btnCopyToClipboard" class="btn btn-secondary" data-clipboard-text="@Model.OutPutText">Copy below text</button>
    

    Then inside a script tag include this

    <script type="application/javascript">
    $(function() {
        new Clipboard('#btnCopyToClipboard');
    });
    </script>
    

    That's it. No compatibility issues. The library will do the job.