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?
Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.
select() The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.
The DOM Input select() method selects all the text content of a textarea or an input element which contains the text field. Syntax: element. select();
/** * Select text between 2 elements. Support selection of continuous elements. * @param {Object} element1 begin element. * @param {Object} element2 end element. */ function selectBetweenTwoElements(element1, element2) { if (window.getSelection) { /* all browsers, except IE 8 and IE 7 */ var selection = window.getSelection(); selection.removeAllRanges(); var range = document.createRange(); range.setStart(element1, 0); range.setEnd(element2, 1); selection.addRange(range); } else { /* works fine in IE 8 / IE 7 */ if (document.body.createControlRange) { var range1 = document.body.createTextRange(); range1.moveToElementText(element1); var range2 = document.body.createTextRange(); range2.moveToElementText(element2); var range = document.body.createTextRange(); range.setEndPoint("StartToStart", range1); range.setEndPoint("EndToEnd", range2); range.select(); } } }
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_intro.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);
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