Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript trigger selection start

It's possible to trigger selection start via javascript/jQuery?

In my opinion, mouse text selection can be divided into these steps:

1) trigger mousedown event and start selection

2) trigger mousemove and move "end point" of selection

3) trigger mouseup and stop selection

It's possible to trigger just step 1) i.e. on text in span element... ...so after that, moving mouse cursor will behave like selection waiting for mouseup?

Or how is implemented and how browser knows that selection starts?

Rangy library: I know this javascript library for creating custom range selection. But it's seems to me too much complicated, to simulate own selection via mouse events. I just want to tell to browser, that I started selection at (span,offset 2) and it should continue at step 2).

like image 636
user775175 Avatar asked Nov 06 '12 13:11

user775175


1 Answers

You can use the mouse events on the selectable element and the document to control when you want to begin and end selection and when you want to test selection etc.

Then during selection you can use window.getSelection() to get information on the current selection.

Try something like this:

var m_MouseDown = false;

document.getElementById('selectMyContent').onmousedown = function (e) {
    m_MouseDown = true;
};

document.onmouseup = function (e) {
    m_MouseDown = false;
};

document.onmousemove = function(e) {
    if (m_MouseDown) {
        document.getElementById('showTextHere').innerHTML = getSelectionInfo();
    }        
}

function getSelectionInfo() {
    var selected = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                var range = sel.getRangeAt(i);

                var txt = document.createElement('div');
                txt.appendChild(range.cloneContents());
                selected = range.startContainer.parentNode.id + ':' + range.startOffset + '-' + range.endOffset + ' "' + txt.innerHTML + '"';
            }
        }
    }
    return selected;
}

See http://jsfiddle.net/nY328/10/ for an example.

like image 124
Rob Hardy Avatar answered Sep 28 '22 07:09

Rob Hardy