Select / copy text using JavaScript or jQuery

I heard that you cannot copy text (in a browser) without using something like Flash; so is there any way to select text using binding and javascript or jQuery.

<p>Text to be copied</p> <a>Copy Text Above</a> 
+4
source share
4 answers

Given the following html example:

 <div class="announcementInfoText"> <p class="copyToClipboard"> <a id="selectAll">Select All Text</a> </p> <textarea ID="description" class="announcementTextArea">This is some sample text that I want to be select to copy to the clipboard</textarea> </div> 

you can select the text in the text box with the following jQuery:

 $("#selectAll").click(function () { $(this).parents(".announcementInfoText").children("textarea").select(); }); 

Now that the text “This is some sample text that I want to select to copy to the clipboard” is selected, you can simply press Ctrl + C and the text will be copied to the clipboard.

+2
source

In new browsers, you can do this to select and copy. This is a pure Javascript solution.

 function copy_text(element) { //Before we copy, we are going to select the text. var text = document.getElementById(element); var selection = window.getSelection(); var range = document.createRange(); range.selectNodeContents(text); selection.removeAllRanges(); selection.addRange(range); //add to clipboard. document.execCommand('copy'); } 

This copy command works in all major browsers: Chrome, Firefox (Gecko), Internet Explorer, and Opera, with the exception of Safari.

+15
source

The simplest solution without starting the plugin based on flash code would look something like this:

 $('a').click(function() { window.prompt('Press ctrl/cmd+c to copy text', $(this).prev('p').text()); }); 

http://jsfiddle.net/JFFvG/

+3
source

I found this jQuery solution:

 $(function() { $('input').click(function() { $(this).focus(); $(this).select(); document.execCommand('copy'); $(this).after("Copied to clipboard"); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" value="copy me!" /> 

A source

0
source

Source: https://habr.com/ru/post/1440877/


All Articles