Select the text with javascript and show the Android copy window.

I want to press a button and automatically select text from input, then I want Android users to see a “copy window” to copy the 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> 
+6
source share
2 answers

As mentioned above, I would not recommend changing the copy and paste function of the android / ios function .. Usually users are familiar with the os-copy-paste functions. You just need to make sure your text is selectable.

However, you can try copying the text to the "clipboard" as described here: How to copy to the clipboard in JavaScript? but I have never tried this using mobile devices and I don’t know if it works

+2
source

I'm not sure which version of Android this will work on, but you should try using the Selection Object . I tried it on 4.3 and it looks like it does what you need.

As a note, although the following warning is indicated on the page:

This is an experimental technology.

Since this technology specification has not stabilized, check the compatibility table for the correct prefixes for use in different browsers. Also note that the syntax and behavior of experimental technology may change in future versions of browsers as the specification changes.

Unfortunately, the mentioned link of the compatibility table does not lead anywhere. Here is a link to the Browser Compatibility Table for window.selection , which, unfortunately, is also not useful.

Here is an 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 this helps.

+1
source

All Articles