javascriptmousesimulate

Can I simulate text selection with the mouse in JavaScript?


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?


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