Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use JavaScript to select text in a pre node/block?

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.

like image 722
Alice Wonder Avatar asked Nov 05 '11 10:11

Alice Wonder


2 Answers

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."

like image 122
Peter Lada Avatar answered Oct 07 '22 12:10

Peter Lada


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();
    }
}
like image 40
Tim Down Avatar answered Oct 07 '22 13:10

Tim Down