Monday, April 16, 2012

JavaScript convert mouse position to selection range

I would like to be able to convert the current mouse position to a range, in CKEditor in particular.



The CKEditor provides an API for setting the cursor according to a range:



var ranges = new CKEDITOR.dom.range( editor.document );
editor.getSelection().selectRanges( [ ranges ] );


Since CKEditor provides this API, the problem may be simplified by removing this requirement and just find a way to produce the range from the mouse coordinates over a div containing various HTML elements.



However, this is not the same as converting a mouse coordinate into the cursor position in a textarea since textareas have fixed column widths and row heights where the CKEditor renders HTML through an iframe.



Based on this, it looks like the range may be applied to elements.



How would you figure out the start/end range which is closest to the current mouse position?



Edit:
An example of how one might use the ckeditor API to select a range on the mouseup event.



editor.document.on('mouseup', function(e) {
this.focus();
var node = e.data.$.target;

var range = new CKEDITOR.dom.range( this.document );
range.setStart(new CKEDITOR.dom.node(node), 0);
range.collapse();

var ranges = [];
ranges.push(range);
this.getSelection().selectRanges( ranges );
});


The problem with the above example is that the event target node (e.data.$.target) is only firing for nodes such as HTML, BODY, or IMG but not for text nodes. Even if it did, these nodes represent chunks of text which wouldn't support setting the cursor to the position of the mouse within that chunk of text.





No comments:

Post a Comment