views:

575

answers:

2

Hello,

I would like to select text on the page by simulating a left mouse button down and drag it to a specified x,y location (in pixels)

Can this be done with JavaScript?

Thank you.

A: 

as far as I know that can't be done. the only text you can select is in a form element (textarea, input text etc.)

dusoft
+5  A: 

I don't think its possible to control the mouse in this way using JavaScript.

However, you can select parts of a document directly using JavaScript. For example:

var h3s = document.getElementsByTagName("h3");
var range = document.createRange();
range.selectNode(h3s[0]);
window.getSelection().addRange(range);

would select the first h3 element.

Also see: http://www.quirksmode.org/dom/range%5Fintro.html for more info about building ranges.

To select the entire body of a document, you can use:

var body = document.getElementsByTagName("body")[0];
var range = document.createRange();
range.selectNode(body);
window.getSelection().addRange(range);

To select the 3rd character of, say, the 4th paragraph in a document, try:

var p4 = document.getElementsByTagName("p")[3].firstChild;
var range = document.createRange();
range.setStart(p4, 2);
range.setEnd(p4, 3);
window.getSelection().addRange(range);
Andy
Can I also select until the middle of the element.. like, letter #3?Also, is your example capable to select lets say a body element, that contains various divs, fonts, etc. ?
thedp
Yes -- see edited post.
Andy

related questions