Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select text with javascript and show Android's copy window

I want to click on button and auto select text from an input, then I want android users to see "copy window" to copy selected text.

enter image description here

<button id="toggler">Click me</button>
<input id="copy_me" type="text" value="Stack Overflow" />

<script>
$('#toggler').click(function() {
  $('#copy_me').select();
  // Some code to fire
});
</script>
like image 330
Vasil Nikolov Avatar asked Mar 27 '14 19:03

Vasil Nikolov


2 Answers

As mentioned in the comment above, I wouldn't recommend changing the copy-paste function of android/ios.. Usually, users are familiar with their os-copy-paste functions. You just need to ensure that your text is selectable.

However, you could try to copy your text into "clipboard" as described here: How do I copy to the clipboard in JavaScript? , but I've never tried this with mobile devices and don't know if it works

like image 131
longi Avatar answered Oct 12 '22 08:10

longi


I'm not sure which versions of Android this will work for, but what you should to try to use is the Selection Object. I tried it on 4.3 and it seems to do what you need.

As a note though the page specifies the following warning:

This is an experimental technology.

Because this technology's specification has not stabilized, check the compatibility table for the proper prefixes to use in various browsers. Also note that the syntax and behavior of an experimental technology is subject to change in future versions of browsers as the spec changes.

Unfortunately the compatibility table link mentioned doesn't lead anywhere. Here's a link to the Browser compatibility table for window.selection which unfortunately is not useful as well.

Here's a quick example:

HTML:

<strong>Text to select</strong>
<button onClick="selectText();">Select</button>

Javascript:

function selectText()
{
    //select the element you want
    var strongs = document.getElementsByTagName("strong");
    //get the selection object
    var selection = window.getSelection();

    if (selection.rangeCount > 0)
    {
        //clear current selection
        selection.removeAllRanges();
    }

    for (var i=0;i<strongs.length;i++)
    {
        //loop over the items and add them to the selection object
        var range = document.createRange();
        range.selectNode(strongs[i]);
        selection.addRange(range);
    }
}

I hope that helps.

like image 26
Faris Avatar answered Oct 12 '22 09:10

Faris