Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

    /**
     * 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();
            }
        }
    }

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top