I understand the security reasons behind dis-allowing JS copying arbitrary text to the clipboard, but is there a method by which clicking a button can select the text in a pre node similar to how the select() function works in an input?
I am not looking for the jQuery plugin that copies to clipboard. I just want to text in pre block to be highlighted so user can ctrl-c to copy.
I seem to finding squat.
This is what you need:
var clip = function(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
};
And the html:
<pre onclick="clip(this);" id="copy_paste"></pre>
Or if you want to programmatically do this:
clip(document.getElementById("copy_paste"));
Or in jquery:
clip($("#copy_paste")[0]);
You cannot pass the jquery element clip() as argument el. It will give "TypeError: Argument 1 of Range.selectNodeContents does not implement interface Node."
It's not too hard. You need separate branches for IE < 9 and all other browsers. Here's a function to select the contents of an element:
Live demo: http://jsfiddle.net/yQa2w/
Code:
function selectElementContents(el) {
if (window.getSelection && document.createRange) {
// IE 9 and non-IE
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.body.createTextRange) {
// IE < 9
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With